在数组中查找重复项并仅打印一次

我试图遍历我的数组并找到所有重复多次的数字:

EG:如果有1 1 2 3 4

应打印说“1次重复”

这是我的代码,到目前为止我尝试了,但它打印所有重复并继续,如果有4 4 4 4 3 6 5 6 9 ,它将打印所有的4,但我不想要:

 class average { public static void main(String[] args) throws IOException { int numOfLines = 0; int sum = 0, mean = 0, median = 0, lq = 0, uq = 0; int[] buffer; File myFile = new File("num.txt"); Scanner Scan = new Scanner(myFile); while(Scan.hasNextLine()) { Scan.nextLine(); numOfLines++; } Scan.close(); Scan = new Scanner(myFile); System.out.println("Number Of Lines: " + numOfLines); buffer = new int[numOfLines]; for(int i=0; i<numOfLines; i++) { buffer[i] = Scan.nextInt(); } Scan.close(); Scan = new Scanner(myFile); for(int i=0; i<buffer.length; i++) { sum = sum+i; mean = sum/numOfLines; } System.out.println("Sum: " + sum); System.out.println("Mean: " + mean); for(int i=0; i<buffer.length; i++) { for(int k=i+1; k<buffer.length; k++) { if(buffer[k] == buffer[i]) { System.out.println(buffer[k]); } } } 

只需将您将找到重复的数字添加到某些结构(如HashSetHashMap以便稍后在检测到其他重复时找到它。

 Set printed = new HashSet(); for(int i=0; i 

更好的O(n)算法:

 Set printed = new HashSet(); for(int i=0; i 

您对arrays的每个项目执行检查,包括前4 ,第2 4等等。 这就是为什么它不会停止并且每个重复元素多次打印消息。

您说您不能使用Set ,并且您不想对数据进行排序。 我的建议是你遍历数组并将每个重复的项添加到列表中。 确保检查是否已添加该项目。 (或使用Set :))

然后遍历列表并打印这些项目。

我会使用HashMap来存储我在数组中遇到的值,将count作为值。 因此,如果您遇到4,您将在HashMap查找它,如果它不存在,您将添加值为1,否则增加返回的值。

您可以循环遍历HashMap并获取所有值并打印数组中遇到的重复项数。

 Integer[] ints = {1, 1, 2, 3, 4}; System.out.println(new HashSet(Arrays.asList(ints))); 

输出:[1,2,3,4]

使用集合解决此问题要简单得多并且可能更快。 但是,根据要求,这里的答案使用“只是简单的数组[s]”而没有排序。 我试图不要过多地更改你的代码但是在exception的情况下我拒绝泄漏资源。

 import java.io.*; import java.util.Arrays; import java.util.Scanner; class Average { public static void main(String[] args) throws IOException { int numOfLines = 0; int sum = 0, mean = 0, median = 0, lq = 0, uq = 0; int[] buffer; int flag = -1; File myFile = new File("num.txt"); try (Scanner Scan = new Scanner(myFile)) { while(Scan.hasNextLine()) { Scan.nextLine(); numOfLines++; } } try (Scanner Scan = new Scanner(myFile)) { System.out.println("Number Of Lines: " + numOfLines); buffer = new int[numOfLines]; for(int i=0; i 

输入文件“num.txt”(由换行符分隔的数字不是逗号):

 1, 2, 3, 4, 5, 6, 7, 2, 1, 7, 9, 1, 1, 3 

输出:

 Number Of Lines: 14 Sum: 91 Mean: 6 Dupes: [1, 2, 3, 7] 

使用apache commons CollectionUtils.getCardinalityMap(collection):

  final Integer[] buffer = {1, 2, 3, 4, 5, 6, 7, 2, 1, 7, 9, 1, 1, 3}; final List list = Arrays.asList(buffer); final Map cardinalityMap = CollectionUtils.getCardinalityMap(list); for (final Map.Entry entry: cardinalityMap.entrySet()) { if (entry.getValue() > 1) { System.out.println(entry.getKey()); } } 

cardinalityMap的toString()在init之后如下所示:

 {1=4, 2=2, 3=2, 4=1, 5=1, 6=1, 7=2, 9=1} 

使用标准java

  final Integer[] buffer = {1, 2, 3, 4, 5, 6, 7, 2, 1, 7, 9, 1, 1, 3}; final List list = Arrays.asList(buffer); final Set set = new LinkedHashSet(list); for (final Integer element: set) { if (Collections.frequency(list, element) > 1) { System.out.println(element); } }