[C++] 1 Pass, easy understood code, using count of zeros


  • 0
    X

    remember how many there are zeros so far, and move it to the proper place.

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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.