将优先级队列更改为最大优先级队列 [英] Change priorityQueue to max priorityqueue

查看:43
本文介绍了将优先级队列更改为最大优先级队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在整数 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.

这篇关于将优先级队列更改为最大优先级队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆