Java O(n) solution


  • 0
    H

    using a counter to zeros and when it comes to a nonzero number, it will know the distance to move.

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

Log in to reply
 

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