Java O(n) 0ms solution


  • 5
    D

    Initially set number of zeros to zero. Increment number of zeros if a zero is found. Otherwise, shift the current element to the left by the total number of zeros. Finally, append zeros at the end of the array.

    public void moveZeroes(int[] nums) {
        int numZeros=0;
        for(int i=0; i<nums.length; i++){
            if(nums[i]==0) numZeros++;
            else nums[i-numZeros]= nums[i];
        }
        for(int i= nums.length - numZeros; i<nums.length; i++) nums[i]=0;
    }

Log in to reply
 

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