LintCode-[容易] 539. 移动零

描述:

给一个数组 nums 写一个函数将 0 移动到数组的最后面,非零元素保持原数组的顺序

注意事项:

1.必须在原数组上操作
2.最小化操作数

样例:

给出 nums = [0, 1, 0, 3, 12], 调用函数之后, nums = [1, 3, 12, 0, 0].

思路:

遍历一遍向量,把所有的 0 项删除,并记录 0 的个数,最后在向量后面加上这个数量的 0 。

C++实现:

class Solution {
public:
    /**
     * @param nums an integer array
     * @return nothing, do this in-place
     */
    void moveZeroes(vector<int>& nums) {
        // Write your code 
        vector<int>::iterator it;
        int count = 0;
        for (it = nums.begin(); it != nums.end(); ) {
            if ((*it) == 0) {
                count++;
                it = nums.erase(it);
            }
            else {
                it++;
            }
        }
        for (int i = 0; i < count; i++) {
            nums.push_back(0);
        }
    }
};

你可能感兴趣的:(c++,lintcode,-LintCode-)