这是当今 Java 中最常见的面试问题。有许多技术可以在 java 中查找数组中的重复元素,比如使用 Collections.frequency()。我正在编写另一个更容易和快速的解决方案。
这里的整数数组有 10 个整数,1 和 8 是重复的整数。你需要过滤掉它们。
package com.cundage.interview; import java.util.HashSet; import java.util.Set; public class DuplicateInArray { public static void main(String[] args) { int[] array = {1,1,2,3,4,5,6,7,8,8}; Set<Integer> set = new HashSet<Integer>(); for(int i = 0; i < array.length ; i++) { //If same integer is already present then add method will return FALSE if(set.add(array[i]) == false) { System.out.println("Duplicate element found : " + array[i]); } } } } Output: Duplicate element found : 1 Duplicate element found : 8
在此解决方案中,您所要做的就是逐个迭代数组和集合中的所有元素。如果 Set.add() 方法返回 false,则元素已经存在于集合中,因此它是重复的。
快乐学习!!
地址:https://www.cundage.com/article/find-duplicate-elements-in-an-array.html