leetcode347. The first k high-frequency elements (hash heap)

Ideas

What the question ultimately needs to return is the first k elements with the highest frequency. It is conceivable that with the help of the data structure of the heap, the elements after the k frequency do not need to be processed, and the time complexity is further optimized.

Insert picture description here
The specific operation is:

  • With the hash table to create digital maps and their occurrences, again traversing frequency array element statistics
  • Maintain a minimum heap with k elements
  • Compare the new element with the top element (the element with the lowest frequency in the heap) each time
  • If the frequency of the new element is greater than the element at the top of the heap, pop the element at the top of the heap and add the new element to the heap
  • Finally, the k elements in the heap are the first k high-frequency elements

time complexity

Insert picture description here

Code

class Solution {
public:
    struct cmp{
    bool operator()(const pair<int, int>& lhs, const pair<int, int>& rhs) {
		return lhs.second > rhs.second;
    }
};
    vector<int> topKFrequent(vector<int>& nums, int k) {
        map<int, int>m;
        //利用哈希表记录每个整数出现的次数
        for(int i=0;i<nums.size();++i)
            m[nums[i]]++;

        //建立小顶堆
        priority_queue<pair<int, int>,vector<pair<int, int>>,cmp> que;
        for(map<int, int>::iterator it=m.begin();it!=m.end();++it)
        {
            que.push(*it);
            if(que.size()>k) que.pop();
        }
        //返回结果
        vector<int>result;
        for(int i=k-1;i>=0;--i)
        {
            result.push_back(que.top().first);
            que.pop();
        }
        return result;
    }
};

Guess you like

Origin blog.csdn.net/weixin_45019830/article/details/115308863