本文介紹了如何在優(yōu)先級隊列中使用Pair,然后使用鍵作為優(yōu)先級返回值的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
所以我想使用最小的鍵作為優(yōu)先級,然后返回相應(yīng)鍵的值:
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是最小的密鑰。即使將值用作優(yōu)先級并返回密鑰也沒問題,因為如果需要,我可以只交換數(shù)據(jù)。我希望使用值/鍵作為優(yōu)先級來顯示鍵/值(在本例中為最小值)。我不知道在這種情況下如何做到這一點。這在C++中運(yùn)行良好。
推薦答案
您需要使用將用于對此優(yōu)先級隊列進(jìn)行排序的Comparator
。
創(chuàng)建PriorityQueue
時使用Comparator.comparing()
并傳遞比較參數(shù)的Method reference
PriorityQueue<Pair<Integer,Integer> > pq=
new PriorityQueue<Pair<Integer,Integer>>(n, Comparator.comparing(Pair::getKey));
或
您可以使用lambda表達(dá)式
PriorityQueue<Pair<Integer,Integer> > pq=
new PriorityQueue<Pair<Integer,Integer>>(n,(a,b) -> a.getKey() - b.getKey());
這篇關(guān)于如何在優(yōu)先級隊列中使用Pair,然后使用鍵作為優(yōu)先級返回值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,