Givena non-empty array of integers, return the k mostfrequent elements.
Forexample,
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.
这一题要求运行时间为O(n log n),对于这种题目,要求你取出现次数最多的k个数,可以使用一个unorder_map统计各个数字出现的次数然后遍历unorder_map,将其中的每一个pair<int,int>反转,放入map<int,int>中或者是priority_queue中,这是因为这两种数据结构到都有自动排序的功能,不同的是map是按照键值从小到大排序,而priority_queues是按照其中的值从大到小排序,值得一提的是,假如priority_queues中存的值是pair<int,int>类型的话,priority_queues中的值会按照pair的key的值从大到 小的顺序排列,这一点要注意
不过这一题使用priority_queues更加好一些,因为优先队列使用大根堆,其功能单一,而map比较优先级队列多出了更多的功能,其代价就是运行时间的延长,以后在做题的时候,当需要一个数组,将数据一个一个的输入,并且排序,然后输出前n个数,记得使用优先级队列这个数据结构,优先级队列使用的是堆排序,取前n大的数或者是前n小的数其效率是极高的
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
vector<int> result;
unordered_map<int, int> store;
for (int u: nums)
{
store[u]++;
}
priority_queue <pair<int, int>> mark;
for (auto u : store)
{
mark.push(pair<int, int>(u.second, u.first));
}
for (int i = 0; i < k; i++)
{
result.push_back(mark.top().second);
mark.pop();
}
return result;
}
};