在代碼中給出一串字符串,我們返回流中k個最長的字符串。我的問題是比較器是如何工作的?我知道我們正在使用一個匿名函數來重寫比較方法來比較兩個字符串的長度,但這個比較如何創建一個最小堆?最小堆是如何創建的?
public static List<String> topK(int k, Iterator<String> iter) {
PriorityQueue<String> minHeap = new PriorityQueue<>(k, new Comparator<String>() {
public int compare(String s1, String s2) {
return Integer.compare(s1.length(), s2.length());
}
});
while (iter.hasNext()) {
minHeap.add(iter.next());
if (minHeap.size() > k) {
// Remove the shortest string. Note that the comparison function above
// will order the strings by length.
minHeap.poll();
}
}
return new ArrayList<>(minHeap);
}
您是否閱讀過PriorityQueue的javadoc? https://docs.oracle.com/javase/9/docs/api/java/util/PriorityQueue.html –
很難理解你在問什麼。 「這個比較如何創造一個最小的堆」這個問題是不合情理的。比較*不會創建最小堆。 'PriorityQueue'代碼通過使用您提供的比較器來訂購堆中的項目來創建最小堆。請澄清你的問題。 –