Scan the vector by two pointers.

  • 0
    class Solution {
    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( i!=j ){
                    nums[i] = nums[j];
        // all of the left should be zero.
        for(; i<size; ++i){


Log in to reply

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