“代码随想录”刷题记录。总结笔记均会放在“算法刷题-代码随想录”该专栏下,以下为原文的链接。
代码随想录此题链接
给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1]
提示:
1 <= nums.length <= 105
k 的取值范围是 [1, 数组中不相同的元素的个数]
题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的
public int[] topKFrequent(int[] nums, int k) {
HashMap<Integer,Integer> match =new HashMap();
for(int num : nums){
match.put(num,match.getOrDefault(num,0) + 1);
}
PriorityQueue<int[]> heap = new PriorityQueue<>(
(pair1,pair2) -> pair1[1] - pair2[1]
);
for(Map.Entry<Integer,Integer> en : match.entrySet()){
if(heap.size() < k){
heap.add(new int[]{en.getKey(),en.getValue()});
}else{
if(heap.peek()[1] < en.getValue()){
heap.poll();
heap.add(new int[]{en.getKey(),en.getValue()});
}
}
}
int[] result = new int[k];
for(int i = heap.size() - 1;heap.size() > 0;i--){
result[i] = heap.poll()[0];
}
return result;
}
``
空间复杂度:O(n)
时间复杂度:O(nlogn(k))
Java语言方面
相关堆的API