Duplicates in a sorted java array
Posted
by
Max Frazier
on Stack Overflow
See other posts from Stack Overflow
or by Max Frazier
Published on 2013-10-18T03:50:07Z
Indexed on
2013/10/18
3:53 UTC
Read the original article
Hit count: 194
I have to write a method that takes an array of ints that is already sorted in numerical order then remove all the duplicate numbers and return an array of just the numbers that have no duplicates. That array must then be printed out so I can't have any null pointer exceptions. The method has to be in O(n) time, can't use vectors or hashes. This is what I have so far but it only has the first couple numbers in order without duplicates and then just puts the duplicates in the back of the array. I can't create a temporary array because it gives me null pointer exceptions.
public static int[] noDups(int[] myArray) {
int j = 0;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] != myArray[j]) {
j++;
myArray[j] = myArray[i];
}
}
return myArray;
}
© Stack Overflow or respective owner