所以我想使用最小的键作为优先级,然后返回对应键的VALUE:
import javafx.util.Pair;
import java.util.PriorityQueue;
public class Test
{
public static void main (String[] args)
{
int n = 5;
PriorityQueue <Pair <Integer,Integer> > l = new PriorityQueue <Pair <Integer,Integer> > (n);
l.add(new Pair <> (1, 90));
l.add(new Pair <> (7, 54));
l.add(new Pair <> (2, 99));
l.add(new Pair <> (4, 88));
l.add(new Pair <> (9, 89));
System.out.println(l.poll().getValue());
}
}
我寻找的输出是 90,因为 1 是最小的键。即使该值用作优先级并且返回键也很好,因为如果需要,我可以交换数据。我想使用值/键作为优先级(在本例中为最小值)来显示键/值。我不知道在这种情况下如何做到这一点。这在 C++ 中工作得很好。
您需要使用
Comparator
来排序此优先级队列。
创建
Comparator.comparing()
时使用
Method reference
并传递比较参数
PriorityQueue
PriorityQueue<Pair<Integer,Integer> > pq=
new PriorityQueue<Pair<Integer,Integer>>(n, Comparator.comparing(Pair::getKey));
或者
您可以使用 lambda 表达式
PriorityQueue<Pair<Integer,Integer> > pq=
new PriorityQueue<Pair<Integer,Integer>>(n,(a,b) -> a.getKey() - b.getKey());
或者,使用实现
Pair
的自定义 Comparable
类。
class Pair implements Comparable<Pair> {
Integer value;
Integer index;
public Pair(Integer value, Integer index) {
this.value = value;
this.index = index;
}
@Override
public int compareTo(Pair o) {
return value - o.value;
}
}
然后使用
// Add elements
queue.add(new Pair(valueKey, index));
// do it for all your elements
final Pair min = queue.poll();
Integer index = min.index;
Integer value = min.value;
// Do with them what you want.
我在leetcode挑战赛中使用了PriorityQueue。 https://leetcode.com/problems/merge-k-sorted-lists/discuss/630580/Using-PriorityQueue-in-Java
在大多数情况下我更喜欢使用 Map.Entry 来实现此目的。其他时候,在 PriorityQueue 构造函数中使用具有 Comparator 的自定义 Pair 类。
import java.util.PriorityQueue;
import java.util.Map;
import java.util.HashMap;
public class Test
{
public static void main (String[] args)
{
int n = 5;
PriorityQueue <Map.Entry<Integer,Integer>> l = new PriorityQueue <> (n,(a,b)->Integer.compare(a.getKey(),b.getKey()));
Map<Integer,Integer> map = new HashMap<>();
map.put(1,90);
map.put(7,54);
map.put(2,99);
map.put(4,88);
map.put(9,89);
l.addAll(map.entrySet());
System.out.println(l.poll().getValue());
}
}
这对我有用
val pq = PriorityQueue<Pair<Int, Int>>(compareBy { it.first })