我被要求编写自己的实现来删除数组中的重复值。这是我创建的内容。但是在测试了100万个元素后,它需要很长时间才能完成。是否有什么方法可以改进我的算法或者消除任何错误?
我需要编写自己的实现 - 不使用Set
, HashSet
等工具或迭代器。只需使用数组来删除重复项。
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;
}
Set<Integer>
吗? - sanbhat