Reputation: 3162
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:
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
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