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);