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.
将一个数组中的所有的0都移到最后面
备注:
你必须就地完成,不得复制该数组。
最小化总共的操作数。
解法1
思路
很简单,依次判断是不是0,如果是就删掉,最后记录删了几个0补上就行。然后提交,一步步改成这样的。。惨不忍睹啊
最开始用的FOR循环,但是,发现如果用erase的话,每次删除完元素后的指向有变动,比如数组是 0 0 1 (会直接略过中间的0),或者 1 0 (会指向没有构造的空间)的时候都会出错
然后让它选择性的i++, 就可以了
class Solution {
public:
void moveZeroes(vector<int>& v) {
if(v.size()==1 && v[0]==0)
return ;
int n=0;
auto i=v.begin();
while(i!=v.end())
{
if(*i == 0)
{
v.erase(i);
n++;
if(i==v.end())
break;
}
else
i++;
}
for(int i=0; i<n; i++)
v.push_back(0);
}
};
解法2
弄完我的渣渣代码后,果断去寻找大神的解法了
思路:
将非0的数向前移,如果前面没有碰到0(也就是j和i同步),那么就相当于自己和自己交换(不变),如果碰到0,那么i和j就有了差,差多少就是有多少个0,最后补上就行了
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int j = 0;
// move all the nonzero elements advance
for (int i = 0; i < nums.size(); i++) {
if (nums[i] != 0) {
nums[j++] = nums[i];
}
}
for (;j < nums.size(); j++) {
nums[j] = 0;
}
}
};
啥时候才能写出大神的方法呢#24