Java one pass O(n) solution


  • 0
    R

    Use a flag to keep tracking is there any zero in between, if yes, when find a none zero value, swap with (last None Zero + 1).

    class Solution {
        public void moveZeroes(int[] nums) {
            int lastNoneZero = -1;
            boolean hasZeroBetween = false;
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] != 0) {
                    if (hasZeroBetween) {
                        nums[lastNoneZero+1] = nums[i];
                        nums[i] = 0;
                        lastNoneZero++;
                        continue;
                    }
                    lastNoneZero = i;
                } else {
                    hasZeroBetween = true;
                }       
            }
        }
    }
    

Log in to reply
 

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