【发布时间】:2018-09-26 04:50:16
【问题描述】:
我正在尝试学习如何使用 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;
}
更值得注意的是,我想知道这条线在做什么:
PriorityQueue<String> heap = new PriorityQueue<String>(
(w1, w2) -> count.get(w1).equals(count.get(w2)) ?
w2.compareTo(w1) : count.get(w1) - count.get(w2) );
有人可以用跛脚的术语解释这里发生了什么吗?有没有办法将比较器重写为常规的“if”语句?
感谢您的帮助。
【问题讨论】:
-
"如果计数相等,则按字母顺序比较,否则按计数比较"。
标签: java data-structures priority-queue