您的位置:首页 > 其它

【LeetCode】283. Move Zeroes

2016-01-07 13:16 274 查看

Problem

Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

Note:

You must do this in-place without making a copy of the array.

Minimize the total number of operations.

Analyze

假设给你开一个辅助数组,你会怎么做?

——把非0的元素放到辅助数组中,略过0元素,最后在辅助数组末端添加足够的0即可。

时间复杂度O(n)。

不开辅助数组呢?

——其实还是一样,只不过原数组的空间可以复用。当没有0时,自然无须移动,当至少出现一个0时,当前待移动的非0元素前面必然至少有一个空闲位置可以使用(0位视为空闲)。

My code

class Solution {
public:
void moveZeroes(vector<int>& nums) {
vector<int>::iterator pos = nums.begin();
for (vector<int>::iterator num = nums.begin(); num != nums.end(); num++) {
if ((*num)) {
if (num != pos) (*pos) = (*num);
pos++;
}
}
for (; pos != nums.end(); pos++ ) (*pos) = 0;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: