LeetCode347. Top K Frequent Elements【map+priority_queue解法】

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].

Note: 

  • 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.
class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        std::unordered_map<int, int> map;
        for (auto val : nums) {
            ++map[val];
        }
        using mapiter = std::unordered_map<int, int>::iterator;
        std::priority_queue<mapiter, std::vector<mapiter>, function<bool(const mapiter&,const mapiter&)>> queue(
            [](const mapiter& p1, const mapiter& p2) { return p1->second > p2->second;});
        for (auto it = map.begin(); it != map.end(); it++)
        {
            if (queue.size() < k) {
                queue.push(it);
            }
            else if (it->second > queue.top()->second){
                queue.pop();
                queue.push(it);
            }
        }
        std::vector<int> vi(k);
        for (int i = k-1; i >= 0; i--)
        {
            auto it = queue.top();
            vi[i] = it->first;
            queue.pop();
        }
        return vi;
    }
};




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章