题目链接:https://leetcode.com/problems/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.
思路: 用一个hash表计数所有的元素, 然后将其以元素个数为key放入优先队列中去, 然后取出前k个就是了, 涉及到两个比较高级的数据结构, unordered_map, 和priority_queue, 另外优先队列因为是以计数为key, 所有要将元素和其计数以pair的形式入队列, 然后要将计数值为pair的第一个, 元素值为第二个. 之后取出优先队列的前k个数就是了.
代码如下:
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> hash;
vector<int> result;
for(auto val: nums) hash[val]++;
priority_queue<pair<int, int>> que;
for(auto val: hash) que.push(make_pair(val.second, val.first));
while(k--)
{
auto val= que.top();
result.push_back(val.second);
que.pop();
}
return result;
}
};