Simple O(n) C++ Solution


  • 1
    Y
    class Solution {
    public:
        vector<int> topKFrequent(vector<int>& nums, int k) {
            unordered_map<int, int> freq;
            for (int num : nums) {
                ++freq[num];
            }
            vector<pair<int, int>> pa;
            for (auto p : freq) {
                pa.push_back(make_pair(-p.second, p.first));
            }
            nth_element(pa.begin(), pa.begin() + k, pa.end());
            vector<int> res;
            for (int i = 0; i != k; ++i) {
                res.push_back(pa[i].second);
            }
            return res;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.