DCh*_*123 4 java priority-queue data-structures
我正在尝试学习如何使用 PriorityQueue,因为我以前从未使用过。这是我在 LeetCode 上找到的一个正在使用的示例,用于解决在字符串数组中查找前 K 个元素的问题
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> count = new HashMap();
for (String word: words) {
count.put(word, count.getOrDefault(word, 0) + 1);
}
PriorityQueue<String> heap = new PriorityQueue<String>(
(w1, w2) -> count.get(w1).equals(count.get(w2)) ?
w2.compareTo(w1) : count.get(w1) - count.get(w2) );
for (String word: count.keySet()) {
heap.offer(word);
if (heap.size() > k) heap.poll();
}
List<String> ans = new ArrayList();
while (!heap.isEmpty()) ans.add(heap.poll());
Collections.reverse(ans);
return ans;
}
Run Code Online (Sandbox Code Playgroud)
更值得注意的是,我想知道这条线在做什么:
PriorityQueue<String> heap = new PriorityQueue<String>(
(w1, w2) -> count.get(w1).equals(count.get(w2)) ?
w2.compareTo(w1) : count.get(w1) - count.get(w2) );
Run Code Online (Sandbox Code Playgroud)
有人可以用跛脚人的话解释这里发生了什么吗?有没有办法将比较器重写为常规的“if”语句?
谢谢你的帮助。
您在构造函数中的表达式是lambda 表达式。因为Comparator是函数式接口,也就是说,它是一个只有一个抽象方法的接口,所以 lambda 表达式可以用作创建匿名类的简写。
在你的例子中,
new PriorityQueue<String>((w1, w2) -> count.get(w1).equals(count.get(w2)) ? w2.compareTo(w1) : count.get(w1) - count.get(w2));
Run Code Online (Sandbox Code Playgroud)
在功能上等同于
new PriorityQueue<String>(new Comparator<String>() {
public int compare(String w1, String w2) {
return count.get(w1).equals(count.get(w2)) ? w2.compareTo(w1) : count.get(w1) - count.get(w2);
}
});
Run Code Online (Sandbox Code Playgroud)
这也与创建一个实现 的单独类并将该类Comparator<String>的实例作为参数传递给PriorityQueue.
至于将 theComparator写成 if 语句,简短的回答是,不。比较器必须是 的实例Comparator<String>。但是,也许更易于理解的相同比较器的版本如下:
new PriorityQueue<String>((w1, w2) -> {
if (count.get(w1).equals(count.get(w2))) { // If the counts of w1 and w2 are the same,
return w2.compareTo(w1); // Then return the reverse lexicographical ordering of w1 and w2 (e.g. "Zebra" comes before "Apple")
} else if (count.get(w1) < count.get(w2)) {
return -1; // w1 comes before w2
} else {
return 1; // w1 comes after w2
}
});
Run Code Online (Sandbox Code Playgroud)
注意:“词典顺序”本质上是按字母顺序排列,但基于 ASCII 代码。有关更多信息,请参阅String#compareTo(String)
希望这可以帮助!