简体   繁体   English

查找和删除数组中的int重复项

[英]Find and remove int duplicates in an Array

First, I know there is a lot of duplicate answers already, but I can't find what I want, even searched in Google. 首先,我知道已经有很多重复的答案,但是我找不到想要的答案,即使在Google中搜索也是如此。 This is a question asked in an interview. 这是面试中提出的一个问题。

So, for my question: I have the next int array: 所以,对于我的问题:我有下一个int数组:

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

EDIT: You can assume that the array is sorted. 编辑:您可以假定该数组已排序。

I want to get only the distinct values, without the duplicates, meaning: 我只想获得不同的值,而没有重复的意思:

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

EDIT: Assume that you don't need to shrink the array, but return the values in their sorted order, and the rest of the values at the end. 编辑:假设您不需要收缩数组,而是按其排序顺序返回值,并在末尾返回其余值。

There is a couple of instructions: 有一些说明:

  1. Don't use any other or new array, meaning use the same array for returning the result. 不要使用任何其他数组或新数组,这意味着使用相同的数组来返回结果。
  2. Don't use any Collections like Set or ArrayList. 不要使用Set或ArrayList之类的任何Collection。
  3. Make it the most useful you can. 使其成为最有用的。

Iv'e tried to do this with Set, but now I want something different. 我试图用Set做到这一点,但现在我想要一些不同的东西。 Also tried to replace the duplicate values with -1 value, but this is true only when I'm assuming that I'm using positive values only. 还尝试将重复的值替换为-1值,但这仅在我假设仅使用正值时才成立。

If you find identical question, tell me and I will delete this one. 如果您发现相同的问题,请告诉我,我将删除此问题。

Thanks. 谢谢。

If they're in order, that's not terribly difficult. 如果他们是有秩序的,那并不是很难。

/**
 * 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;
}

After that, only the first w elements are interesting. 之后,只有前w元素有趣。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM