347 Top K Frequent Elements

Given a non-empty array of integers, return the k most frequent elements.
For example,

Given [1,1,1,2,2,3] and k = 2, return [1,2].
  • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  • Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

Solution

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> frequency;
        priority_queue<pair<int, int>> topK;
        int n = nums.size();
        for ( int i = 0; i <= n-1; i++ ) {
            if ( frequency.find(nums[i]) == frequency.end() ) frequency[nums[i]] = 1;
            else frequency[nums[i]] += 1;
        }
        int count = 0;
        for ( auto it = frequency.begin(); it != frequency.end(); it++ ) {
            if ( count < k ) {
                topK.push(pair<int, int>(-it->second, it->first)); 
                count += 1; continue;
            }
            if ( -it->second < topK.top().first ) {
                topK.pop();
                topK.push(pair<int, int>(-it->second, it->first));
                continue;
            }
        }
        vector<int> res;
        while ( ! topK.empty() ) {
            res.push_back(topK.top().second);
            topK.pop();
        }
        return res;
    }
};

Notes

  • Use a minimum heap of size K. When a new frequency K_new is added, if K_new is larger than the heap's top frequency, we pop out the top element and push in the new frequency.
  • Note the use of priority_queue. (Store negative number for minimum heap.)
    topK.push(pair<int>(-frequency, element));
    topK.pop();
    int f = -topK.top().first;
    int number = topK.top().second;
    
  • We have a pair of something, the default comparison is made according to the first element in the pair.

results matching ""

    No results matching ""