Note:
首先遍历一边数组,统计一下每个元素出现的次数,最多出现n次
开个长度为n的数组,出现次数放进去,1、 2、 3都出现了两次,那么s[2] = 3
表示3个数出现了两次
然后从大到小开始枚举s数组,找出现次数前K多的,比如说找到了s[4] = 3,减完3之后正好找到了,那么也就是说,我只需要找出现次数是4及以上的就可以了
遍历一开始统计的出现次数,只要是出现次数在4以上的,就放到答案数组中
代码如下:
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> hash;
for(auto n: nums) hash[n] ++;
vector<int> map(nums.size() + 1);
for(auto [x, c]: hash) map[c] ++;
int i = nums.size(), t = 0;
while(t < k) t += map[i --];
vector<int> ans;
for(auto [x, c]: hash)
if(c > i) ans.push_back(x);
return ans;
}
};