【发布时间】:2020-04-29 23:26:20
【问题描述】:
public static void printOrganizedList(int[] array) {
int[] temp = array;
System.out.println("N Count");
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++;
}
}
for(int n = i-1; n > 0; n--) {
if(array[n] == array[i]) {
break;
}
else {
System.out.println(array[i] + " " + count);
}
}
}
}
此方法用于接收一个数组并打印重复值以及它在数组中出现的次数。像这样:
-12, 3, -12, 4, 1, 1, -12, 1, 1, 2, 3, 4, 2, 3, -12
The program output should be:
N Count
4 2
3 3
2 2
1 4
-1 1
-12 4
我的问题是,无论我尝试什么,该方法总是吐出重复的数字及其重复次数,重复次数与重复次数一样多。所以不是输出
"-12 4"
它会输出:
"-12 4"
"-12 4"
"-12 4"
"-12 4"
我也知道有更先进和更有效的技术,但我们还没有学到很多东西。 提前致谢。
【问题讨论】:
-
是否允许使用 HashMap 来存储输入数组中数字的计数/频率?
-
我们可以使用我相信的任何东西,但我无法向他证明我使用哈希图的合理性,因为我们还没有这样做。