347.前K个高频元素
给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1]
提示:
1 <= nums.length <= 105k的取值范围是[1, 数组中不相同的元素的个数]- 题目数据保证答案唯一,换句话说,数组中前
k个高频元素的集合是唯一的
题解:
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
if (!map.containsKey(num)) {
map.put(num, 1);
} else {
map.put(num, map.get(num) + 1);
}
}
// 优先队列按照map的value进行升序排序
PriorityQueue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
return map.get(a) - map.get(b);
}
});
// 遍历map
// 因为是优先队列,所以插入元素后会进行排序,在queue长度>=k时,当前队头元素的值如果小于带插入的值就会移除队头元素,把元素e插入
// 这样就能维护一个长度为k,且排序规则为自定义的优先队列,最后把优先队列转成数组返回出去即可
map.entrySet().forEach(e -> {
if (queue.size() < k) {
queue.add(e.getKey());
} else if (e.getValue() > map.get(queue.peek())) {
queue.remove();
queue.add(e.getKey());
}
});
return queue.stream().mapToInt(Integer::intValue).toArray();
}
}