
hash计数,然后导到vector里排序,再取出前k项。
vector<int> topKFrequent(vector<int>& nums, int k) {
map<int,int> hash;
for(int i=0;i<nums.size();++i){
++hash[nums[i]];
}
vector<pair<int,int>> vec;
for(auto it=hash.begin();it!=hash.end();++it){
vec.push_back(*it);
}
sort(vec.begin(),vec.end(),[=](pair<int,int> a,pair<int,int> b){
return a.second > b.second;
});
vector<int> res;
for(int i=0;i<k;++i){
res.push_back(vec[i].first);
}
return res;
}
本文介绍了一种高效查找数组中出现频率最高的前K个元素的算法。通过使用哈希表统计每个元素的出现次数,将数据导入向量并进行排序,最后返回前K个最频繁的元素。该方法适用于需要快速识别数据集中主要趋势或模式的应用场景。
425





