leetcode 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:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

简单题,直接用内置函数就搞定了。remove(it1,it2,c)算法是遍历整个vector,发现等于c的元素就用后一个元素值来替代当前元素值。vector整体的size()不变。(比如对1234这个序列remove 2,返回的序列是 1344(3被复制到2的位置,4被复制到3的位置))。然后返回一个迭代器(第一个是c的位置的迭代器)。

当然,如果不知道remove函数或者fill函数,手写一下这个过程也很简单。

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        fill(remove(nums.begin(),nums.end(),0),nums.end(),0);
    }
};

 

posted @ 2016-04-20 04:23  周洋  阅读(157)  评论(0编辑  收藏  举报