如何檢測原生 Java 陣列中的重複值?
要檢測陣列中的重複值,需要將陣列的每個元素與其他所有元素進行比較,如果匹配,則獲得重複的元素。
實現此目的的一種方法是需要使用兩個迴圈(巢狀),其中內迴圈從 i+1(其中 i 是外迴圈的變數)開始,以避免比較中的重複。
示例
import java.util.Arrays;
import java.util.Scanner;
public class DetectDuplcate {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array that is to be created::");
int size = sc.nextInt();
int[] myArray = new int[size];
System.out.println("Enter the elements of the array ::");
for(int i=0; i<size; i++) {
myArray[i] = sc.nextInt();
}
System.out.println("The array created is ::"+Arrays.toString(myArray));
System.out.println("indices of the duplicate elements :: ");
for(int i=0; i<myArray.length; i++) {
for (int j=i+1; j<myArray.length; j++) {
if(myArray[i] == myArray[j]) {
System.out.println(j);
}
}
}
}
}輸出
Enter the size of the array that is to be created :: 6 Enter the elements of the array :: 87 52 87 63 41 63 The array created is :: [87, 52, 87, 63, 41, 63] indices of the duplicate elements :: 2 5
解決方案 2: 除了上述方法外,我們還有更可靠的解決方案
集合介面不允許重複的元素,因此,建立一個集合物件並嘗試使用 add() 方法向其中新增每個元素,如果重複元素,則該方法返回 false
示例
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class DetectDuplcateUsingSet {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array that is to be created::");
int size = sc.nextInt();
int[] myArray = new int[size];
System.out.println("Enter the elements of the array ::");
for(int i=0; i<size; i++) {
myArray[i] = sc.nextInt();
}
System.out.println("The array created is ::"+Arrays.toString(myArray));
System.out.println("indices of duplicate elements in the array are elements::");
Set set = new HashSet();
for(int i=0; i<myArray.length; i++) {
if(!set.add(myArray[i])) {
System.out.println(i);
}
}
}
}輸出
Enter the size of the array that is to be created :: 5 Enter the elements of the array :: 78 56 23 78 45 The array created is :: [78, 56, 23, 78, 45] indices of duplicate elements in the array are elements:: 3
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP