Ofir A.
Ofir A.

Reputation: 3162

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. This is a question asked in an interview.

So, for my question: I have the next int array:

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.
  3. Make it the most useful you can.

Iv'e tried to do this with Set, but now I want something different. 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.

If you find identical question, tell me and I will delete this one.

Thanks.

Upvotes: 1

Views: 2431

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382132

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.

Upvotes: 9

Related Questions