java - 如何获取此列表以打印数组中的重复值而不打印两次值
问题描述
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 轻松实现。您可以创建一个 Hashmap,它将元素保存为键并将出现次数保留为值。
public static void printOrganizedList(int[] array) {
System.out.println("N Count");
HashMap<Integer, Integer> countMap = new HashMap<>();
for (int i = 0; i < array.length; i++){
if (countMap.containsKey(array[i])){
int count = countMap.get(array[i]);
countMap.replace(array[i], count + 1);
}else{
countMap.put(array[i], 1);
}
}
Iterator iterator = countMap.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry mapElement = (Map.Entry) iterator.next();
int key = (int) mapElement.getKey();
int count = (int) mapElement.getValue();
System.out.println(key + " " + count);
}
}
此外,您编写的程序的时间复杂度达到 O(N^2),这对于大型程序来说可能是一个非常大的瓶颈。
上面带有 hashmap 实现的程序只会花费你 O(N)
推荐阅读
- java - Kotlin 不允许 charAt
- nginx - nginx中lister [::]:80的含义
- java - 在光标进入对象之前按下鼠标时,如何检测光标何时悬停在对象上?
- jenkins - 根据选择的带参数的管道构建并行运行多个 jmeter 脚本
- dart - 我们如何在 dart 中创建不可扩展的类
- javascript - 如何在 Mapbox 中将地图限制为地理区域?
- c# - 如何使用 c# 运算符检查字符串是否不包含两个值之一?
- powershell - 无法使用 ansible 更新 AD 域组的 objectClass 属性
- storybook - 故事书组件库站点?
- go - 在golang中将字符串转换为日期