Given asortedinteger array, remove duplicate 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 array after deduplication.

Assumptions

  • The given array is not null

Examples

  • {1, 2, 2, 3, 3, 3} → {1, 2, 2, 3, 3}

Solution: exclude i,保留k个,则array[j]与array[i - k]比较

  public int[] dedup(int[] array) {
    if (array.length < 3) {
      return array;
    }
    int i = 2, j = 2;
    while (j < array.length) {
      if (array[j] != array[i - 2]) { //注意不是if(array[j] != array[j - 2]),因为是要slow左边保留2份
        array[i] = array[j];
        i++;
      }
      j++;
    }
    return Arrays.copyOf(array, i);
  }

results matching ""

    No results matching ""