返回顶部

[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.

Example:

Input: [0,1,0,3,12]
Output: [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.

思路:从头扫到尾,记录当前已经出现的0的数目c,每当出现一个0就把当前当前非0的a[i]赋值给a[i-c]。

 1 class Solution {
 2 public:
 3     void moveZeroes(vector<int>& nums) 
 4     {       
 5         int size = nums.size();
 6         int count=0;
 7         for(int i = 0;i<size;i++)
 8         {
 9             if(nums[i] == 0)
10                 count++;
11             if(count!=0 && nums[i]!=0)
12             nums[i-count] =nums[i]; 
13         }
14         for(int i = size-count;i<size;i++)
15             nums[i]=0;
16     }
17 };

刷题尚未成功,同志仍需努力,与诸君共勉。

posted @ 2019-07-13 14:27  Swetchine  阅读(105)  评论(0编辑  收藏  举报