程式語言 - LeetCode - CPP - 347. Top K Frequent Elements



參考資訊:
https://www.cnblogs.com/grandyang/p/5454125.html

題目:


解答:

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> freq;
        for (int n : nums) {
            freq[n] += 1;
        }

        priority_queue<pair<int, int>> q;
        for (auto& [n, cnt] : freq) {
            q.push({ cnt, n });
        }

        vector<int> ans;
        for (int i = 0; i < k; ++i) {
            ans.push_back(q.top().second);
            q.pop();
        }

        return ans;
    }
};