I was asked to write my own implementation to remove duplicated values in an array. Here is what I have created. But after tests with 1,000,000 elements it took very long time to finish. Is there something that I can do to improve my algorithm or any bugs to remove ?
I need to write my own implementation - not to use Set
, HashSet
etc. Or any other tools such as iterators. Simply an array to remove duplicates.
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;
}
How about this one, only for sorted array of numbers, to print array without duplicates, without using Set or other Collections, just Array:
Array of 1040 duplicated numbers processed in 33020 nanoseconds(0.033020 millisec).
Heres a simpler, better way to do this using arraylists instead:
Hope this helps or solves the purpose.
This is not using Set, Map, List or any extra collection, only two arrays:
And the main to test it
And the output:
This is an interview question :Remove duplicates from an array.I shall not use any Set or collections. The complete solution is :