本文最后更新于:2022年9月6日 晚上
给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
示例 1:
示例 2:
提示:
- 你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
- 你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。
- 题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的。
- 你可以按任意顺序返回答案。
Solution
参考 @liuyubobobo 、代码随想录
- 利用优先队列,底层为堆实现,std::greater 构造小顶堆
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int,int> freq; for(int i = 0 ; i < nums.size() ; i ++ ) freq[nums[i]] ++;
assert(k <= freq.size());
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pq; for(auto iter = freq.begin(); iter != freq.end(); iter ++ ){ if(pq.size() == k){ if(iter->second > pq.top().first){ pq.pop(); pq.push( make_pair(iter->second, iter->first)); } } else pq.push(make_pair(iter->second , iter->first)); }
vector<int> res; while(!pq.empty()){ res.push_back(pq.top().second); pq.pop(); } return res; } };
|
- 利用优先队列,底层为堆实现,自己实现 compare 函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| class Solution { public: class mycomparison { public: bool operator()(const pair<int, int>& lhs, const pair<int, int>& rhs) { return lhs.second > rhs.second; } }; vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int, int> map; for (int i = 0; i < nums.size(); i++) { map[nums[i]]++; }
priority_queue<pair<int, int>, vector<pair<int, int>>, mycomparison> pri_que; for (unordered_map<int, int>::iterator it = map.begin(); it != map.end(); it++) { pri_que.push(*it); if (pri_que.size() > k) { pri_que.pop(); } }
vector<int> result(k); for (int i = k - 1; i >= 0; i--) { result[i] = pri_que.top().first; pri_que.pop(); } return result;
} };
|
java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public int[] topKFrequent(int[] nums, int k) { int[] result = new int[k]; HashMap<Integer, Integer> map = new HashMap<>(); for (int num : nums) { map.put(num, map.getOrDefault(num, 0) + 1); }
PriorityQueue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>( (o1, o2) -> o1.getValue() - o2.getValue() ); for (Map.Entry<Integer, Integer> entry : map.entrySet()) { queue.offer(entry); if (queue.size() > k) { queue.poll(); } } for (int i = k - 1; i >= 0; --i) { result[i] = queue.poll().getKey(); } return result; } }
|