LeetCode-283. Move Zeroes

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.

题解:

主要都是先将非零的元素提出来,可以用vector先存起来,也可以用原数组来存,用两个计数器,将非零元素先放到a[0,1,2,3...]中,最后剩余的就是0了

void moveZeroes(vector<int>& nums) {
    int lastNonZeroFoundAt = 0;
    for (int i = 0; i < nums.size(); i++) {
        if (nums[i] != 0) {
            nums[lastNonZeroFoundAt++] = nums[i];
        }
    }
   
    for (int i = lastNonZeroFoundAt; i < nums.size(); i++) {
        nums[i] = 0;
    }
}


posted @ 2017-11-05 19:56  link98  阅读(101)  评论(0编辑  收藏  举报