修正0347.前K个高频元素Java简易版代码注释

This commit is contained in:
dxiaofeng
2023-10-24 10:52:23 +08:00
parent bd06d78ed6
commit 097051e1bb

View File

@ -193,7 +193,7 @@ class Solution {
class Solution {
public int[] topKFrequent(int[] nums, int k) {
// 优先级队列,为了避免复杂 api 操作pq 存储数组
// lambda 表达式设置优先级队列从大到小存储 o1 - o2 为从大到o2 - o1 反之
// lambda 表达式设置优先级队列从大到小存储 o1 - o2 为从小到大o2 - o1 反之
PriorityQueue<int[]> pq = new PriorityQueue<>((o1, o2) -> o1[1] - o2[1]);
int[] res = new int[k]; // 答案数组为 k 个元素
Map<Integer, Integer> map = new HashMap<>(); // 记录元素出现次数
@ -204,6 +204,7 @@ class Solution {
tmp[0] = x.getKey();
tmp[1] = x.getValue();
pq.offer(tmp);
// 下面的代码是根据小根堆实现的我只保留优先队列的最后的k个只要超出了k我就将最小的弹出剩余的k个就是答案
if(pq.size() > k) {
pq.poll();
}