347. Top K Frequent Elements
Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
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.
解法:统计前K个高频数字。考虑用HashMap来做,建立数字和其出现次数的映射,然后再按照出现次数进行堆排序。在C++中使用priority_queue来实现,默认是最大堆。
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> maps;
priority_queue<pair<int, int>> que;
vector<int> res;
for (auto num : nums)
++maps[num];
for (auto iter : maps)
que.push({ iter.second, iter.first });
for (int i = 0; i < k; ++i) {
res.push_back(que.top().second);
que.pop();
}
return res;
}
};
还没有评论,来说两句吧...