Scan the vector by two pointers.


  • 0
    class Solution {
    public:
    void moveZeroes(vector<int>& nums) {
        int size=nums.size();
        int i=0;
        // i < j. i points to the last of the final vector
        for(int j=0; j<size; ++j){
            // if meet non-zero, then move it  to i and let i move forward.
            if(nums[j]){
                if( i!=j ){
                    nums[i] = nums[j];
                }
                ++i;
            }
        }
        // all of the left should be zero.
        for(; i<size; ++i){
            nums[i]=0;
        }
    }
    

    };


Log in to reply
 

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