347. Top K Frequent Elements
Posted qiang-wei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.
方案1:桶排序
class Solution { public: // 桶排序 vector<int> topKFrequent(vector<int>& nums, int k) { vector<vector<int>>bucket(nums.size() + 1); unordered_map<int, int> fre; for (auto num: nums) { if(fre.find(num) == fre.end()) { fre[num] = 1; } else { fre[num] = fre[num] + 1; } } for (auto f: fre) { bucket[f.second].push_back(f.first); } vector<int> res; for (int i = bucket.size() - 1; i >= 0 ; --i) { if (!bucket[i].empty()) for (auto b : bucket[i]) { res.push_back(b); if (res.size() == k)return res; } } return res; } };
方案二:利用优先队列
class Solution { public: // 桶排序 vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int, int> fre; for (auto num: nums) { fre[num]++; } vector<int> res; // 优先队列 priority_queue<pair<int, int>> pq; for (auto f: fre) { pq.push(make_pair(f.second,f.first)); if (pq.size() > fre.size() - k) { res.push_back(pq.top().second); pq.pop(); } } return res; } };
以上是关于347. Top K Frequent Elements的主要内容,如果未能解决你的问题,请参考以下文章