题目所属分类
哈希 + 计数排序
原题链接
给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。
代码案例:输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
提示:
1 <= nums.length <= 105
k 的取值范围是 [1, 数组中不相同的元素的个数]
题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的
进阶:你所设计算法的时间复杂度 必须 优于 O(n log n) ,其中 n 是数组大小。
题解
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer,Integer> map = new HashMap<>();
for(int c :nums){
map.put(c , map.getOrDefault(c , 0) + 1);
}
//cnt[i]表示出现i次的元素有cnt[i]个
int[] cnt = new int[nums.length+1];
for(int a : map.values()){
cnt[a]++ ;
}
//寻找分界点:从后往前遍历,直到下标凑够k
//遍历完n的值即为分界点,出现次数比n大的数都是正确答案
int m = 0 ; int n = nums.length ;
while(m != k){
m += cnt[n];
n -- ;
}
int [] res = new int[k];
int i = 0 ;
for(Integer t : map.keySet()){
if(map.get(t) > n){
res[i++] = t ;
}
}
return res;
}
}