Given an array nums, write a function to move all zeros to the end of the array while preserving the relative order of the non-zero elements.

Input:,1,0,3,12 [0]

Output:,3,12,0,0 [1]

They want to move all the 0 elements to the end, which is equal to move all the non-0 elements to the head.

  public void moveZeroes(int[] nums) {
        // A non-zero pointer records the latest position of a non-zero number
        int j = 0;

        for (int i = 0; i < nums.length; i++) {
            if(nums[i] ! =0) {// If j and I overlap then there is no need to swap
                if(j ! = i){ nums[j] = nums[i]; nums[i] =0; } j ++; }}}Copy the code

The method of double pointer is used here, one pointer records the latest position of the non-zero number, and one pointer records the position of the current traversal number group.

Complexity analysis

  • Time complexity: O(n)O(n)O(n) only traverses an array of length N once
  • Space complexity: O(1)O(1)O(1) only requires constant space to store several variables.