Given an integer array(not guaranteed to be sorted), remove adjacent repeated elements. For each group of elements with the same value keep at most two of them. Do this in-place, using the left side of the original array and maintain the relative order of the elements of the array. Return the final array.

Assumptions

  • The given array is not null

Examples

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

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

Solution: 注意与II的区别,循环continue的条件是array[j] == array[i - 1] && array[j] == array[i - 2],不是array[j] == array[i - 2]

  public int[] dedup(int[] array) {
    if (array.length < 3) {
      return array;
    }
    int i = 2;
    for (int j = 2; j < array.length; j++) {
      if (array[j] == array[i - 1] && array[j] == array[i - 2]) {
        continue;
      }
      array[i++] = array[j];
    }
    return Arrays.copyOf(array, i);
  }

results matching ""

    No results matching ""