如何计算和仅打印重复项? [英] how to count and print out only duplicates?
本文介绍了如何计算和仅打印重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道如何遍历整个数组,但是我只需要重复出现的次数.我是初学者,所以只是循环和数组的基本用法.
I know how to go through whole array, but I only need number of duplicate occurrences. I'm at beginners level, so just basic use of loops and arrays.
int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
for (int i = 0; i < array.length; i++) {
int count = 0;
for (int j = 0; j < array.length; j++) {
count++;
}
System.out.println(array[i] + "\toccurs\t" + count + "X");
}
推荐答案
如果您不仅仅使用循环和数组,则可以做得更好,但是一种简单的算法是使用两个嵌套的 for
循环,并在其中放置 if
语句,当发现重复项时该计数器将递增计数器.
You can do better if you use more than just loops and arrays, but a simple algorithm would be to use two nested for
loops, and put an if
statement inside that increments a counter when a duplicate is found.
int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
for (int i = 0; i < array.length - 1; i++) {
int count = 1;
for (int j = i + 1; j < array.length; j++) {
if (array[i] == array[j]) {
count++;
}
}
if (count > 1) {
System.out.println(array[i] + "\toccurs\t" + count + " times");
}
}
这篇关于如何计算和仅打印重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文