给你一个整数数组 nums
和一个整数 k
,请你返回其中出现频率前 k
高的元素。你可以按 任意顺序 返回答案。
示例 1:
示例 2:
提示:
1 <= nums.length <= 105
k
的取值范围是 [1, 数组中不相同的元素的个数]
- 题目数据保证答案唯一,换句话说,数组中前
k
个高频元素的集合是唯一的
进阶:你所设计算法的时间复杂度 必须 优于 O(n log n)
,其中 n
是数组大小。
解题思路
先将元素存储在map<元素,出现频率>中
思路一:按照元素出现的频率创建大顶堆,只需要移除k次大顶堆的第一个元素就能得到答案。但实际上不需要建立大小为n的堆
思路二:创建小顶堆,保持小顶堆的大小为k,因为小顶堆第一个元素是最小的元素,只要遍历的元素大于堆顶,就将堆顶的元素移除,最终留下的k个元素就是频率最高的k个元素
基于大顶堆的实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution { public static int[] topKFrequent(int[] nums, int k) { Map<Integer,Integer> map = new HashMap<>(); for(int num : nums){ map.put(num,map.getOrDefault(num,0)+1); }
PriorityQueue<int[]> pq = new PriorityQueue<>((pair1, pair2)->pair2[1]-pair1[1]); for(Map.Entry<Integer,Integer> entry:map.entrySet()){ pq.add(new int[]{entry.getKey(),entry.getValue()}); } int[] ans = new int[k]; for(int i= 0 ; i < k; i++){ ans[i] = pq.poll()[0]; } return ans; } }
|
- 时间复杂度: $O(nlogn)$,每次调整堆的时间复杂度为logn,需要调整n次
- 空间复杂度: $O(n)$
基于小顶堆的实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class Solution { public int[] topKFrequent(int[] nums, int k) { Map<Integer, Integer> map = new HashMap<>(); for(int num : nums){ map.put(num, map.getOrDefault(num, 0) + 1); }
PriorityQueue<int[]> que = new PriorityQueue<>((pair1,pair2) -> pair1[1] - pair2[1]);
for(Map.Entry<Integer, Integer> entry : map.entrySet()){ if(que.size() < k){ que.add(new int[]{entry.getKey(), entry.getValue()}); }else if(entry.getValue() > que.peek()[1]){ que.poll(); que.add(new int[]{entry.getKey(), entry.getValue()}); } }
int[] ans = new int[k]; int index = 0; while(!que.isEmpty()){ ans[index++] = que.poll()[0]; } return ans;
} }
|
- 时间复杂度: $O(nlogk)$,每次调整堆的时间复杂度为logk,需要调整n次
- 空间复杂度: $O(n)$