leetcode347

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

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.
又是统计某个字符个数的类型,可以用无序容器存储,然后通过pair使key和value反置,这样key就是对应出现的次数,value就是对应的数字,而priority_queue可以按照key降序排列,刚好是我们所求的前k个。

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int,int> result;
        for(int num : nums){
            result[num]++;
        }

        vector<int> res;
        priority_queue<pair<int,int>> pq; 
        for(auto it = result.begin(); it != result.end(); it++){
            pq.push(make_pair(it->second, it->first));
            if(pq.size() > result.size() - k){
                res.push_back(pq.top().second);
                pq.pop();
            }
        }
        return res;
    }
};
  • priority_queue为优先级队列,就是根据元素的优先级被读取,接口和queues非常相近。可以通过template参数指定一个排序准则。缺省的排序准则是利用operator< 形成降序排列,那么所谓“下一个元素”就是“数值最大的元素”。
  • 常用的接口:
    push() 将一个元素置于priority queue中。
    top() 返回priority queue中的“下一个元素”,即数值最大的元素。
    pop() 从priority queue 中移除一个元素。
  • pair两种构造的方法
pair<std::string, double> pA("This is a StringTest0.", 9.7); 
pair<std::string, double> pB;  
pB = make_pair("This is a StringTest.", 9.9);  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值