【题目描述】
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].
基本思路就是先遍历一遍将0去掉并记录0的个数,再重现从vector尾部插入相同个数的0.注意当去除0时要将迭代器不要再加一,因为erase()函数会自动将迭代器指向下一个数。
【代码】
class Solution {
public:
void moveZeroes(vector<int>& nums) {
vector <int>::iterator iter1,iter2;
int cnt=0;
for(iter1=nums.begin();iter1!=nums.end();iter1++){
if(*iter1==0){
nums.erase(iter1);
cnt++;
iter1--;
}
}
for(int i=0;i<cnt;i++){
nums.push_back(0);
}
}
};
本文介绍了一种算法,用于将数组中的所有零元素移至末尾,同时保持非零元素的相对顺序不变。通过两次遍历数组,第一次遍历去除零元素并计数,第二次在数组尾部补充相同数量的零。
424

被折叠的 条评论
为什么被折叠?



