如何检测原始 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:除了这个解决方案,我们还有一个更可靠的解决方案
set 接口不允许重复的元素,因此,创建一个 set 对象并尝试使用 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
广告