难度: medium

通过大顶堆的结构来完成此题:
PriorityQueue
> pq = new PriorityQueue<>((o1, o2) -> o2.getValue() - o1.getValue());
如果是 o1.getValue() - o2.getValue()则是小顶堆;
Entry和entrySet:
Entry
由于Map中存放的元素均为键值对,故每一个键值对必然存在一个映射关系。
Map中采用Entry内部类来表示一个映射项,映射项包含Key和Value (我们总说键值对键值对, 每一个键值对也就是一个Entry)
Map.Entry里面包含getKey()和getValue()方法
entrySet是 java中 键-值 对的集合,Set里面的类型是Map.Entry,一般可以通过map.entrySet()得到。
- Set
> entryseSet=map.entrySet(); -
- for (Map.Entry
entry:entryseSet) { -
- System.out.println(entry.getKey()+","+entry.getValue());
-
- }
Java:
- class Solution {
- public int[] topKFrequent(int[] nums, int k) {
- int[] ans = new int[k];
- Map
map = new HashMap<>(); - for (int num: nums) {
- map.put(num, map.getOrDefault(num, 0) + 1);
- }
-
- // entrySet() 常被用于遍历
- Set
> entries = map.entrySet(); - // 构造大顶堆
- PriorityQueue
> pq = new PriorityQueue<>((o1, o2) -> o2.getValue() - o1.getValue()); - for (Map.Entry
entry: entries) { - pq.add(entry);
- // pq.offer(entry);
- }
-
- for (int i = 0; i < k; i++) {
- ans[i] = pq.poll().getKey();
- }
-
- return ans;
- }
- }