我需要一个java代码,它可以删除数组中的重复项,而不需要更改元素的顺序,也不需要使用Sets或排序技术。
如果输入数组为{23,1,5,4,2,23,6,4},则输出应为{23,1,5,4,2,6}
发布于 2015-06-23 10:25:25
您可以在O(n^2)时间使用O(1)额外空间来完成此操作。
public static int[] noSpaceElementDistinctness(int[] arr) {
int n = arr.length;
for (int i = 0; i < n;i++) {
boolean exists = false;
for (int j = 0; j < i; j++) {
if (arr[i] == arr[j]) {
exists = true;
break;
}
}
if (exists) {
for (int j = i+1; j<n; j++)
arr[j-1] = arr[j];
n--;
i--; //to iterate the next element, which is now at index i, not i+1.
}
}
for (int i = n; i < arr.length; i++) arr[i] = Integer.MIN_VALUE; //indicates no value
return arr;
}顺便提一句,元素区分问题并不像乍看上去那么简单,但它是一个严格的下限问题,您可以如何有效地解决它。This thread讨论了这个问题。
发布于 2015-06-23 10:09:57
如果您使用Java 8,一个简单的方法是:
int[] array = {23, 1, 5, 4, 2, 23, 6, 2, 4};
int[] noDupes = IntStream.of(array).distinct().toArray();
System.out.println(Arrays.toString(noDupes)); // [23, 1, 5, 4, 2, 6]发布于 2015-06-23 09:56:11
创建一个新的ArrayList()。循环遍历旧列表,并将值复制到new,除非它已经在其中。
订单会被更改,因为你不会复制所有.
https://stackoverflow.com/questions/30999527
复制相似问题