Thinking process

Two pointers

  • right pointer points to the first position that is not zero
  • replace the value on the left pointer with the value of the right
  • if right reaches to the end of the input array, break the loop
  • if left doesn't reach to the end, replace 0 on the rest of elements

Mistakes

don't need to consider whether left pointer points to 0 or not

public class Solution {
    public void moveZeroes(int[] nums) {
        if (nums.length < 1) return;

        int left = 0;
        int right = 0;

        while (right < nums.length) {
            if (nums[right] != 0) {
                nums[left++] = nums[right];
            }
            right++;
        }

        while (left < nums.length) {
            nums[left++] = 0;
        }

    }
}

results matching ""

    No results matching ""