Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Move Zeroes #34

Open
Open
@cheatsheet1999

Description

@cheatsheet1999

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;
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions