Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move Zeroes #34

Open
cheatsheet1999 opened this issue Sep 12, 2021 · 0 comments
Open

Move Zeroes #34

cheatsheet1999 opened this issue Sep 12, 2021 · 0 comments

Comments

@cheatsheet1999
Copy link
Owner

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;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant