cheatsheet1999/FrontEndCollection

Move Zeroes

cheatsheet1999 opened this issue · 0 comments

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

Screen Shot 2021-09-11 at 11 12 38 PM

var moveZeroes = function(nums) {
    //we do not need to traverse i, just initialize it to 0, and move its index accordingly.
    let i = 0;
    for(let j = 0; j < nums.length; j++) {
        //as long as nums[j] is not 0, we move the num[j] to nums[i], so original num[j] becomes 0. 
        if(nums[j] !== 0) {
            nums[i] = nums[j];
            //since current nums[i] is not 0, we move i
            i++;
        }
    }
    
    //from the position of i, put all 0's until the ned
    for(let k = i; k < nums.length; k++) {
        nums[k] = 0;
    }
}