假设我们想根据值对 HashMap 进行排序。我们实现一个带有比较器的priorityQueue来做到这一点。结果,生成的 pq 从索引 0 到末尾从最大到最小排序。
这是代码:
PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<Map.Entry<Integer, Integer>>(
new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
return o2.getValue() - o1.getValue();
}
});
但是,有人说它是一个maxheap,我理解堆只是父值大于子值,但我不明白为什么它是一个maxheap?它只是在优先级队列中实现比较器?这与堆有何关系?
最佳答案
java中优先级队列的内部结构是堆。
该比较器将用于与优先级队列中的父值进行比较。
关于java - Maxheap 与 PriorityQueue 的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38494734/