283. Move Zeroes
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就删除,然后在末尾插入。
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
/***********************************提交部分*********************************/
class Solution
{
public:
void moveZeroes(vector<int>& nums)
{
vector<int>::iterator p=nums.begin();
int i=1,n=nums.size();
while(i<=n)
{
if(*p==0)
{
vector<int>::iterator p1=p;
p=nums.erase(p1);
nums.push_back(0);
}
else
p++;
++i;
}
}
};
/*******************************************************************************/
int main()
{
int n;
scanf("%d",&n);
vector<int> a;
int tmp;
for(int i=0; i<n; i++)
{
scanf("%d",&tmp);
a.push_back(tmp);
}
Solution s;
s.moveZeroes(a);
for(int i=0; i<n; i++)
printf("%d ",a[i]);
return 0;
}
做这题的时候主要是卡在erase函数的应用,因为平时少用,所以不是很熟悉。现在可以总结几个点:
1.要注意erase函数的形参是一个迭代器,指向要删除的元素,操作成功后返回的也是一个迭代器,指向已删除元素的下一个元素。
2. 循环的条件不能写成for(p=nums.begin(); p!=nums.end(); p++); 原因有二,一是当把所有的0都放到vector后面之后,会陷入死循环;
二是因为如果没有重新定义一个迭代器p1就直接进行erase(p); 操作,p就会成为野指针,p++这步就无法执行,所以必须要重新定义一个迭代器,
且把p赋值为erase(p1),相当于p++,就不用再画蛇添足多写一句p++了。
3. 注意定义迭代器的语法vector<int>::iterator p1,不能写成int *p1,亲测有效。