
解题思路:
哈希表记录元素出现的次数,然后将哈希表元素加入优先队列(会自动根据比较原则去排列元素)
定义优先队列根据元素频率降序排列,然后直接取出前k个元素即可
cpp
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
//1.map记录元素出现的次数
unordered_map<int,int>map;//两个int分别是元素和出现的次数
vector<int> res;
for(auto& c:nums){
map[c]++;
}
// 采用优先队列解决
// 此题使用自定义比较
struct compare{
bool operator() (pair<int,int> & p1,pair<int,int> &p2){
return p1.second > p2.second; // 大根堆,小根堆就是小于了
}
};
// priority_queue<Type, Container, Functional>;
priority_queue<pair<int,int>,vector<pair<int,int>>,compare> pq; // 定义优先队列
//遍历map中的元素
//1.管他是啥,先入队列,队列会自己排序将他放在合适的位置
//2.若队列元素个数超过k,则将栈顶元素出栈(栈顶元素一定是最小的那个)
for(auto &m : map){
pq.push(m);
if(pq.size() > k){
pq.pop();
}
}
while(!pq.empty()){
res.emplace_back(pq.top().first);
pq.pop();
}
return res;
}
};
、