LeetCode 347. Top K Frequent Elements

Top K Frequent Element

class Solution {
public:
    vector topKFrequent(vector& nums, int k) {
        unordered_map mp;
        for (auto n: nums) mp[n]++;
        vector res;
        priority_queue> pq;
        for (auto m: mp) {
            pq.push(make_pair(m.second, m.first));
            if (pq.size() > mp.size() - k) {
                res.push_back(pq.top().second);
                pq.pop();
            }
        }
        return res;
    }
};

你可能感兴趣的:(LeetCode 347. Top K Frequent Elements)