[283]Move Zeroes

来源:互联网 发布:淘宝店是什么意思 编辑:程序博客网 时间:2024/05/22 00:06

【题目描述】

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);        }    }};


0 0
原创粉丝点击