347. 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.
解题思路
O(N + N*longN) 的解法
先用无序哈希表记录数字出现次数,然后插入到最大堆中,最后从堆中取出前 K 个元素并返回。
struct FrequencyCmp {
bool operator() (const pair<int, unsigned int> &lhs, pair<int, unsigned int> &rhs) {
return lhs.second < rhs.second ? true : false;
}
};
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, unsigned int> numberFrequency;
for (auto e : nums) {
numberFrequency[e]++;
}
priority_queue<pair<int, unsigned int>, vector<pair<int, unsigned int>>, FrequencyCmp> heap;
for (auto e : numberFrequency) {
heap.push(e);
}
vector<int> v;
for (int i = 0; i < k; i++) {
v.push_back(heap.top().first);
heap.pop();
}
return v;
}
};