3 回答

TA貢獻1829條經驗 獲得超9個贊
您只想遍歷數組一次。如果你想要的只是重復,你可以簡單地通過跟蹤你在使用之前看到的任何值來做到這一點ArrayList:
int[] data = {5, 6, 1, 6, 9, 5, 2, 1, 5};
System.out.println(Arrays.toString(data));
ArrayList<Integer> seenBeforeList = new ArrayList<>();
for(int index = 0; index < data.length; index++){
int value = data[index];
if(seenBeforeList.contains(value)){
System.out.println("Duplicate Element : " + value);
System.out.println("Index of that duplicate element : " + index);
} else {
seenBeforeList.add(value);
}
}
輸出:
[5, 6, 1, 6, 9, 5, 2, 1, 5]
Duplicate Element : 6
Index of that duplicate element : 3
Duplicate Element : 5
Index of that duplicate element : 5
Duplicate Element : 1
Index of that duplicate element : 7
Duplicate Element : 5
Index of that duplicate element : 8
如果您想按值分組,那么使用 a 更有意義HashMap,將值存儲為鍵,將索引存儲為值。然后簡單地遍歷HashMap.

TA貢獻1863條經驗 獲得超2個贊
(i != j)在您的 if 語句中沒有必要,因為j總是領先i1,但這不是您的問題。
您可以嘗試使用重復數組標志來了解何時已經找到重復項。
import java.util.Arrays;
public class StackOverflow {
public static void main(String args[]) throws Exception {
int[] duplicate_data = {5,6,1,6,9,5,2,1,5};
boolean[] duplicate = new boolean[duplicate_data.length];
System.out.println(Arrays.toString(duplicate_data));
for (int i = 0; i < duplicate_data.length - 1; i++) {
for (int j = i + 1; j < duplicate_data.length; j++) {
// Make sure you haven't flagged this as a duplicate already
if (!duplicate[j] && duplicate_data[i] == duplicate_data[j]) {
duplicate[j] = true;
System.out.println("Duplicate Element : " + duplicate_data[j]);
System.out.println("Index of that duplicate element : " + j);
}
}
}
}
}
結果:
[5, 6, 1, 6, 9, 5, 2, 1, 5]
Duplicate Element : 5
Index of that duplicate element : 5
Duplicate Element : 5
Index of that duplicate element : 8
Duplicate Element : 6
Index of that duplicate element : 3
Duplicate Element : 1
Index of that duplicate element : 7

TA貢獻1776條經驗 獲得超12個贊
它正在再次搜索相同的重復項,因為您沒有以任何方式存儲以前找到的重復項。因此,您必須使用數據結構來存儲以前找到的重復項,而不是再次搜索它們。這讓我們找到了一個更好的解決方案來查找重復項,它從一開始就使用哈希集,因為它是 O(n) 而不是 O(n^2)
import java.io.File;
import java.util.Arrays;
import java.util.Scanner;
public class T1 {
public static void main(String args[]) throws Exception {
Scanner x=new Scanner(new File("C:\\Duplicate_array.txt"));
Set<Integer> set = new HashSet<Integer>();
int index = 0;
while(x.hasNext()){
int nextNumber = x.nextInt();
if (set.contains(nextNumber)) {
System.out.println("Duplicate Element : " + nextNumber);
System.out.println("Index of that duplicate element : "+index);
} else
set.add(nextNumber);
}
}
}
如您所見,使用 時HashSet,我們不需要兩個嵌套for循環。我們可以HashSet在常數時間 O(1) 內測試 a 是否包含一個數字,這消除了逐個元素搜索整個數組以找到重復項的需要。
添加回答
舉報