将 Java PriorityQueue 更改为最大 PQ
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3705881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Changing Java PriorityQueue to a Max PQ
提问by Chris
The Priority Queue implementation in the Java standard library appears to be a min Priority Queue which I found somewhat confusing. In order to turn it into a max one I created a custom comparator object.
Java 标准库中的 Priority Queue 实现似乎是一个 min Priority Queue,我发现这有点令人困惑。为了把它变成最大的,我创建了一个自定义的比较器对象。
Comparator<Integer> cmp = new Comparator<Integer>()
{
public int compare( Integer x, Integer y )
{
return y - x;
}
};
I was wondering if there was a more elegant solution. Essentially I wan't a generic priority queue that could be used to implement Dijkstras etc. I didn't even realise there would be ones which operated in reverse :/
我想知道是否有更优雅的解决方案。本质上,我不想使用可用于实现 Dijkstras 等的通用优先级队列。我什至没有意识到会有反向操作的队列:/
采纳答案by Suman Chitturi
Use Java's Collections.reverseOrder()
comparator.
使用 Java 的Collections.reverseOrder()
比较器。
回答by Michael Barker
If you have an existing comparator you could create a generic inversing comparator.
如果您有一个现有的比较器,您可以创建一个通用的反比较器。
public class InverseComparator<T> implements Comparator<T> {
private final Comparator<T> delegate;
public InverseComparator(Comparator<T> delegate) {
this.delegate = delegate;
}
public int compare(T x, T y) {
return delegate(y, x);
}
}
回答by Crandy
Not sure what you mean by elegant but when I want a PQ implemented like a MaxHeap (used in Dijkstra's) I just use an inline comparator constructor.
不确定您所说的优雅是什么意思,但是当我想要像 MaxHeap(在 Dijkstra 中使用的)一样实现 PQ 时,我只使用内联比较器构造函数。
PriorityQueue<Integer> PQ= new PriorityQueue<Integer>(20, new Comparator<Integer>(){
public int compare(Integer o1, Integer o2){
return o2 - o1;
}
});
It's simple enough for anytime I'm looking for something simple and only want to use the Comparator once.
它足够简单,我正在寻找简单的东西并且只想使用一次比较器。
回答by cyclotrojan
Here is a code snippet using Collections.reverseOrder()
-
这是一个代码片段,使用Collections.reverseOrder()
-
PriorityQueue<Integer> maxPQ = new PriorityQueue<Integer>(20,Collections.reverseOrder());
You also need to provide the initial capacity of the Priority Queue (20 here) along with the Comparator.
您还需要提供优先级队列的初始容量(此处为 20)以及比较器。