mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
更新0347 前K个高频元素
由原来的构建小顶堆改为构建大顶堆,减少部分代码逻辑,并增加了注释 通过LeetCode提交代码,修改后的执行时间更快。
This commit is contained in:
@ -141,13 +141,10 @@ class Solution {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Set<Map.Entry<Integer, Integer>> entries = map.entrySet();
|
Set<Map.Entry<Integer, Integer>> entries = map.entrySet();
|
||||||
// 根据map的value值正序排,相当于一个小顶堆
|
// 根据map的value值,构建于一个大顶堆(o1 - o2: 小顶堆, o2 - o1 : 大顶堆)
|
||||||
PriorityQueue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>((o1, o2) -> o1.getValue() - o2.getValue());
|
PriorityQueue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>((o1, o2) -> o2.getValue() - o1.getValue());
|
||||||
for (Map.Entry<Integer, Integer> entry : entries) {
|
for (Map.Entry<Integer, Integer> entry : entries) {
|
||||||
queue.offer(entry);
|
queue.offer(entry);
|
||||||
if (queue.size() > k) {
|
|
||||||
queue.poll();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
for (int i = k - 1; i >= 0; i--) {
|
for (int i = k - 1; i >= 0; i--) {
|
||||||
result[i] = queue.poll().getKey();
|
result[i] = queue.poll().getKey();
|
||||||
|
Reference in New Issue
Block a user