leetcode283 Move Zeroes

283. Move Zeroes

Total Accepted: 61066 Total Submissions: 140284 Difficulty: Easy

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.

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        vector<int>::iterator it, end;
        end = nums.end();
        for (it = nums.begin(); it != end;)
        {
            if (*it == 0)
            {
                nums.erase(it);
                nums.push_back(0);
                --end;
                continue;
            }
            ++it;
        }
    }
};


發佈了44 篇原創文章 · 獲贊 16 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章