【发布时间】:2021-09-19 05:32:57
【问题描述】:
我正在使用优先级队列来存储 Identity HashMap 的元素(以便也保留重复的键)。我想根据降序的键在优先级队列中添加 IdentityHashMap 的元素并打印它们的索引(从 1 开始)。但它没有给出正确的输出。
这是我的代码:
import java.util.*;
import java.lang.*;
class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
IdentityHashMap<Integer, Integer> hm = new IdentityHashMap<>();
PriorityQueue<Map.Entry<Integer, Integer>> p = new PriorityQueue<>(new my_Comparator());
int size = sc.nextInt();
int a[] = new int[size];
for (int index = 0; index < size; index++) {
a[index] = sc.nextInt();
hm.put(a[index], index + 1);
}
for (Map.Entry<Integer, Integer> temp : hm.entrySet()) {
p.add(temp);
}
while (p.size() != 0) {
Map.Entry<Integer, Integer> temp = p.poll();
System.out.print(temp.getValue() + " ");
}
System.out.println();
}
}
class my_Comparator implements Comparator<Map.Entry<Integer, Integer>> {
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
Integer i1 = o1.getKey();
Integer i2 = o2.getKey();
if (i1.equals(i2)) {
return o2.getValue().compareTo(o1.getValue());
}
return i2.compareTo(i1);
}
}
输入:
8
19 1 8 25 20 12 4 25
正确的输出应该是这样的:
8 4 5 1 6 3 7 2
这些是元素在优先队列中按降序排序后的索引。
我的代码输出是:
8 5 1 6 3 7 2
【问题讨论】:
-
请查看并尝试遵循 Java 代码格式规则。通过遵循这些规则,其他人将更容易阅读和理解您的代码,然后能够帮助您。如果您使用大多数 IDE,它们可以帮助您正确格式化代码。
标签: java sorting hashmap comparator priority-queue