283. Move Zeroes

Source link: https://leetcode.com/problems/move-zeroes/

Design

  1. Initialize a pointer tmp for recording where assignments of 0 should be started.
  2. Traverse through the array, if the current element not equals to 0, assign the element where tmp at with such value, and move the pointer tmp forward, which means the position where assignments of 0 start will be also moving forward.
  3. Start traversing where tmp at to the end of the array, and assign each element passed through with 0.

Implementation

class Solution {
  public void moveZeroes(int[] nums) {
    if (nums == null || nums.length == 1) return;
    int tmp = 0;
    for (int i = 0; i < nums.length; i++) {
      if (nums[i] != 0) nums[tmp++] = nums[i];
    }
    while (tmp != nums.length) {
      nums[tmp++] = 0;
    }
  }
}

Complexity Analysis

Time: $O(n)$

Space: $O(1)$