2 回答
TA贡献1785条经验 获得超4个赞
您可以尝试以下方法:
public static void removedups(int se[]) {
int repeat = 0;
int counter = 0;
if(se.length < 2) {
System.out.println("Array smaller than 2, please change the size!");
return;
}
//Find out all the duplicates and replace with 0
boolean isZeroPresent = false;
int zeroindex = -1;
for(int i = 0; i < se.length; i++) {
for(int j = i + 1; j < se.length; j++) {
if(se[i] == se[j]) {
if(se[i] == 0 && !isZeroPresent) {
isZeroPresent = true;
zeroindex = i;
}
se[j] = 0;
}
}
}
//find the exact count of the array which does not contains duplicates
int customIndex = 0;
for(int i = 0; i < se.length; i++) {
System.out.println(se[i]);
if(isZeroPresent && zeroindex == i) {
customIndex++;
continue;
}
if(se[i] == 0) {
continue;
}
customIndex++;
}
//create new array which will hold all the unique values and return
int arr[] = new int[customIndex];
int j = 0;
for(int i = 0; i < customIndex; i++) {
if(se[i] == 0) {
if(zeroindex == i) {
arr[j] = se[i];
j++;
}
continue;
}
arr[j] = se[i];
j++;
}
System.out.println("-----------------");
printArr(arr);
}
public static void printArr(int arr[]) {
for(int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
TA贡献1859条经验 获得超6个赞
诀窍是有两个索引,一个从 ( i) 读取,一个数组部分的结果索引 ( ) 保持唯一元素。writingI
int[] removeDuplicates(int[] a) {
int writingI = 0;
// Invariant condition:
// writingI <= i
// a[0 <= j < writingI] are all unique
for (int i = 0; i < a.length; ++i) {
int n = a[i];
boolean found = false;
for (int j = 0; j < writingI; ++j) {
if (a[j] == n) {
found = true;
break;
}
}
if (!found) {
a[writingI] = n;
++writingI;
}
}
//return Arrays.copyOf(a, 0, writingI);
int[] result = new int[writingI];
for (int j = 0; j < writingI; ++j) {
result[j] = a[j];
}
return result;
}
我向你展示了这个技巧是如何运作的,我的良心不好。它确实有助于自己挖掘问题并找到解决方案。
添加回答
举报