[leetcode] Move Zeroes 解题报告

题目链接:https://leetcode.com/problems/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.

思路:怒刷了三道水题,睡觉了再见,神秘园真是一个很好听的专辑得意

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int count0 = 0;
        for(int i =0; i< nums.size(); i++)
        {
            if(nums[i] == 0)
                count0++;
            else
                nums[i - count0] = nums[i];
        }
        for(int i = nums.size()- count0; i < nums.size(); i++)
            nums[i] = 0;
    }
};


你可能感兴趣的:(LeetCode,算法,array,数组)