Here is my code for removing duplicated values from an array. I think I tested it with the most possible cases. Any suggestions or bugs?
public static int[] removeDuplicates(int[] arr){
int end = arr.length;
for(int i = 0; i < end; i++){
for(int j = i + 1; j < end; j++){
if(arr[i] == arr[j]){
int shiftLeft = j;
for(int k = j+1; k < end; k++, shiftLeft++){
arr[shiftLeft] = arr[k];
}
end--;
j--;
}
}
}
int[] whitelist = new int[end];
for(int i = 0; i < end; i++){
whitelist[i] = arr[i];
}
return whitelist;
}
After some tests, it appears really inefficient because an array with 1,000,000 elements takes a very long time to end. Is there any better way to implement this on arrays?
EDIT: It's now fixed and more efficient. Are there still any suggestions?
//sorted array of ints as input
public static int[] removeDuplicates(int[] arr){
//dest array index
int destination = 0;
//source array index
int source = 0;
int currentValue = arr[0];
int[] whitelist = new int[arr.length];
whitelist[destination] = currentValue;
while(source < arr.length){
if(currentValue == arr[source]){
source++;
} else {
currentValue = arr[source];
destination++;
source++;
whitelist[destination] = currentValue;
}
}
int[] returnList = new int[++destination];
for(int i = 0; i < destination; i++){
returnList[i] = whitelist[i];
}
return returnList;
}