更新0347 前K个高频元素

由原来的构建小顶堆改为构建大顶堆,减少部分代码逻辑,并增加了注释

通过LeetCode提交代码,修改后的执行时间更快。
This commit is contained in:
AronJudge
2022-07-11 11:06:51 +08:00
parent 50d7e354dd
commit 85e0d6c85d

View File

@ -141,13 +141,10 @@ class Solution {
}
Set<Map.Entry<Integer, Integer>> entries = map.entrySet();
// 根据map的value值正序排,相当于一个小顶堆
PriorityQueue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>((o1, o2) -> o1.getValue() - o2.getValue());
// 根据map的value值构建于一个大顶堆o1 - o2: 小顶堆, o2 - o1 : 大顶堆)
PriorityQueue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>((o1, o2) -> o2.getValue() - o1.getValue());
for (Map.Entry<Integer, Integer> entry : entries) {
queue.offer(entry);
if (queue.size() > k) {
queue.poll();
}
}
for (int i = k - 1; i >= 0; i--) {
result[i] = queue.poll().getKey();