思路一
- 如果我们先遍历一遍,然后用哈希表存储数字出现的个数,那么这道题就和59、数据流的第k大数值一样了
- 注意我们的优先队列保存的是Entry,也就是键值对,对应规则是数字和出现次数
- 如果优先队列的元素是没有实现Comparator接口的,需要我们自己传入比较规则。对于参数 (e1,e2) 如果想让e1在前面,那就返回负值
public 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);
}
Queue<Map.Entry<Integer, Integer>> minHeap = new PriorityQueue<>(Comparator.comparingInt(Map.Entry::getValue));
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if(minHeap.size() < k)
minHeap.offer(entry);
else if(entry.getValue() > minHeap.peek().getValue()){
minHeap.poll();
minHeap.offer(entry);
}
}
return minHeap.stream().mapToInt(Map.Entry::getKey).toArray();
}
}
思路二:快速排序~
这个还木有实现 哈哈 尽快补上