1

首先,我知道已经有很多重复的答案,但我找不到我想要的,甚至在谷歌中搜索。这是面试时提出的问题。

所以,对于我的问题:我有下一个 int 数组:

int[] array = {1, 1, 1, 2, 2, 3, 4, 4, 4, 5, 5, 6, 7, 7, 8, 8, 9, 9};

编辑:您可以假设数组已排序。

我只想获得不同的值,而不是重复的,这意味着:

array = {1, 2, 3, 4, 5, 6, 7, 8, 9, ......};

编辑: 假设您不需要缩小数组,而是按排序顺序返回值,并在最后返回其余值。

有几个说明:

  1. 不要使用任何其他或新数组,这意味着使用相同的数组来返回结果。
  2. 不要使用任何集合,如 Set 或 ArrayList。
  3. 让它尽可能地有用。

我试过用 Set 来做这件事,但现在我想要一些不同的东西。还尝试用 -1 值替换重复值,但这仅在我假设我仅使用正值时才成立。

如果您发现相同的问题,请告诉我,我将删除此问题。

谢谢。

4

1 回答 1

9

如果它们是有序的,那并不是非常困难。

/**
 * removes duplicates in the provided sorted array
 * @return the number of different elements (they're at the beginning)
 */
public static int shrink(int[] array) {
    int w = 0;
    for (int i=0; i<array.length; i++) {
      if (i==0 || array[i]!=array[i-1]) {
          array[w++]=array[i];
      }
    }
    return w;
}

在那之后,只有第一个w元素是有趣的。

于 2012-09-21T12:38:16.903 回答