mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
修正0347.前K个高频元素Java简易版代码注释
This commit is contained in:
@ -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();
|
||||
}
|
||||
|
Reference in New Issue
Block a user