天天看点

LeetCode_347. Top K Frequent Elements

题目描述:

LeetCode_347. Top K Frequent Elements
class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        if(nums.empty()||k>nums.size())
            return {};
        vector<int> res;
        priority_queue<pair<int,int> > que;
        map<int,int> mp;
        for(auto n:nums)
            mp[n]++;
        for(auto it:mp){
            que.push({it.second,it.first});//注意pair对的访问方式使用it.first
        }
        for(int i=0;i<k;i++){
            res.push_back(que.top().second);
            que.pop();
        }
        return res;
    }
};```