【刷题日记】栈和队列-前 K 个高频元素-L347-Medium
给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。
思路
- 使用
map
键值对存储每个元素出现的次数;然后按照出现的次数进行从大到小排序(排序可以用小顶堆优化);最后取前 k 个元素。
- 看了下官解确实是用小顶堆的。
学习点
- 为什么使用小顶堆(什么时候用小顶堆,什么时候用大顶堆)。
- 函数指针
auto cmp = [] (...) { ... };
以及 delctype()
。
代码
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
| class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { map<int, int> ele_freq;
for (int i = 0; i < nums.size(); i++) ele_freq[nums[i]]++;
vector<pair<int, int>> map_eles; for(auto it = ele_freq.begin(); it != ele_freq.end(); it++) { map_eles.emplace_back(pair<int, int>(it->first, it->second)); } auto cmp = [] (pair<int, int> &a, pair<int, int> &b) { return a.second > b.second; }; sort(map_eles.begin(), map_eles.end(), cmp);
vector<int> res; for (int i = 0; i < k; i++) { res.push_back(map_eles[i].first); }
return res; } };
|
使用小顶堆:
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
| class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int, int> map; for (int i = 0; i < nums.size(); i++) { map[nums[i]]++; }
auto cmp = [] (pair<int, int> &a, pair<int, int> &b) { return a.second > b.second; }; priority_queue<pair<int, int>, vector<pair<int, int>>, delctype(cmp)> 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; } };
|