class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
vector<int> result;
auto cmp = [](pair<int, int> a, pair<int, int> b){return a.second > b.second;};
// decltype(cmp) 只是获取 cmp 的类型,但它 不是一个对象,所以 pq(cmp) 需要显式传入 cmp 变量,让 priority_queue 拥有一个实际的比较对象。
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> pq(cmp);
unordered_map<int, int> map;
for(int i = 0; i < nums.size(); i++) {
map[nums[i]]++;
}
for(const auto& value : map) {
pq.emplace(value);
if(pq.size() > k) pq.pop();
}
while(k--) {
result.push_back(pq.top().first);
pq.pop();
}
return result;
}
};
力扣347. 前 K 个高频元素
最新推荐文章于 2025-05-22 10:04:48 发布