我想做一个函数来检查数组中是否有任何数字出现了三次或更多次。
例如这个数组:
4 - 6 - 14 - 8 - 6 - 15 - 14 - 15 - 13 - 10 -
不应该输出任何东西,但是这个:
4 - 6 - 14 - 8 - 6 - 15 - 14 - 15 - 14 - 10 -
systemout 是否应该打印数字 14 存在三次的输出。
这应该怎么做?我开始制作一个 for 循环,
for(int i=0; i<array.length; i++){
}
然后我卡住了,我该怎么做?
最佳答案
for (int i = 0; i < array.length; i++) {
int count = 0;
for (int j = 0; j < array.length; j++) {
{
if (array[i] == array[j]) {
count++;
}
}
if (count >= 3) {
System.out.println(array[i] + " exists " + count
+ " times.");
}
}
}
该程序输出 n 次(对于 n >= 3),表示 an 元素存在 n 次。您应该添加一个逻辑来检查元素是否已经被检查过。但也许你现在可以自己继续了。提示:使用 HashMap 或列表……或者……
其他需要 Integer[]
而不是 int[]
并且速度更快的解决方案:
Integer[] array = new Integer[] { 1, 2, 1, 1, 1, 3, 3, 3, 2, 2, 4, 5 };
for (int i = 0; i < array.length; i++) {
int count = 0;
if (array[i] != null) {
int compare = array[i].intValue();
for (int j = 0; j < array.length; j++) {
if (array[j] != null) {
if (compare == array[j]) {
array[j] = null;
count++;
}
}
}
if (count >= 3) {
System.out
.println(compare + " exists " + count + " times.");
}
}
}
输出:
1 exists 4 times.
2 exists 3 times.
3 exists 3 times.
所以首先将您的数组复制到一个 Integer[] 数组中。后一种算法还解决了输出问题。
关于Java:检查数组中是否存在三个或更多匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5248043/