本文介绍了将优先级队列更改为最大优先级队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在整数 Java 中有优先队列:
I have priority queue in Java of Integers:
PriorityQueue<Integer> pq= new PriorityQueue<Integer>();
当我调用 pq.poll()
时,我得到了最小元素.
When I call pq.poll()
I get the minimum element.
问题:如何修改代码获取最大元素?
Question: how to change the code to get the maximum element?
推荐答案
像这样:
PriorityQueue<Integer> queue = new PriorityQueue<>(10, Collections.reverseOrder());
queue.offer(1);
queue.offer(2);
queue.offer(3);
//...
Integer val = null;
while( (val = queue.poll()) != null) {
System.out.println(val);
}
Collections.reverseOrder()
提供了一个 Comparator
,它将按照与自然顺序相反的顺序对 PriorityQueue
中的元素进行排序在这种情况下.
The Collections.reverseOrder()
provides a Comparator
that would sort the elements in the PriorityQueue
in a the oposite order to their natural order in this case.
这篇关于将优先级队列更改为最大优先级队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!