Easy to understand, three steps to get the result. C++


  • 0
    struct Node {
        int val;
        int count;
        
        bool operator <(Node a) const  {  return count < a.count; }
        bool operator >(Node a) const  {  return count > a.count; }
    };
    
    class Solution {
    public:
        vector<int> topKFrequent(vector<int>& nums, int k) {
            unordered_map<int, int> map;
            priority_queue<Node> pque;
            
            // 1.use map to count.
            for (int item : nums) {
                if (map.find(item) == map.end()) {
                    map[item] = 1;
                } else {
                    map[item] += 1;
                }
            }
            
            // 2.priority_queue to sort.
            for (auto it = map.begin(); it != map.end(); ++ it) {
                pque.push({it->first, it->second});
            }
    
            // 3.get top K into vector.
            vector<int> ret;
            for (int i = 0; i < k; ++ i) {
                Node item = pque.top();
                ret.push_back(item.val);
                pque.pop();
            }
            return ret;
        }
    };

Log in to reply
 

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