#include <iostream>
#include <queue>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
struct cmp {
bool operator() (const pair<int, int>& l, const pair<int, int>& r) {
return l.second > r.second;
}
};
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> m;
for(int num:nums){
m[num]++;
}
priority_queue<pair<int, int>, vector<pair<int, int>>, cmp> que;
for(auto it = m.begin(); it != m.end(); it++) {
que.push(*it);
if (que.size() > k) {
que.pop();
}
}
vector<int> result;
while(!que.empty()) {
result.push_back(que.top().first);
que.pop();
}
reverse(result.begin(), result.end());
return result;
}
};
int main() {
vector<int> nums = {1,1,1,2,2,3};
Solution S;
vector<int> res = S.topKFrequent(nums, 2);
for (auto v : res){
cout << v << " ";
}
cout <<endl;
return 0;
}
C++ top K 元素
最新推荐文章于 2024-04-29 09:30:21 发布