Given an array of integers, move all the 0s to the right end of the array.

The relative order of the elements in the original array need to be maintained.

Assumptions:

  • The given array is not null.

Examples:

  • {1} --> {1}
  • {1, 0, 3, 0, 1} --> {1, 3, 1, 0, 0}

Solution: i左边的为非0元素(exclude i),复制完j后,i把后面的元素置为0

  public int[] moveZero(int[] array) {
    int i = 0;
    for (int j = 0; j < array.length; j++) {
      if (array[j] != 0) {
        array[i] = array[j];
        i++;
      }
    }
    while (i < array.length) {
      array[i] = 0;
      i++;
    }
    return array;
  }

如果不需要保持原来顺序,可以用相撞型指针

  public int[] moveZero(int[] array) {
    if (array == null || array.length < 2) {
      return array;
    } 
    int i = 0, j = array.length - 1;
    while (i < j) {
      if (array[i] != 0) {
        i++;
        continue;
      }
      if (array[j] == 0) {
        j--;
        continue;
      }
      int temp = array[i];
      array[i] = array[j];
      array[j] = temp;
      i++;
      j--;
    }
    return array;
  }

results matching ""

    No results matching ""