Very simple Java O(n) Solution in 4 lines, 1ms


  • 0

    Step 1: Move all non-zero elements forward in the first traversal.
    Step 2: Set all elements to zero from the last non-zero element.

        public void moveZeroes(int[] nums) {
            int C = 0;  // count of zeros
            int N = nums.length;
            for (int i = 0; i < N; i++) {
                if (nums[i] == 0)   C++;
                else if (C != 0)    nums[i-C] = nums[i];
            }
            for (int i = N-C; i < N; i++)   nums[i] = 0;
        }
    
    

Log in to reply
 

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