文章目录
- 堆(特征:第K个数)
- 哈希表(特征:计数)
- [347. 前 K 个高频元素](https://leetcode-cn.com/problems/top-k-frequent-elements/)
- [215. 数组中的第K个最大元素](https://leetcode-cn.com/problems/kth-largest-element-in-an-array/)
- [451. 根据字符出现频率排序](https://leetcode-cn.com/problems/sort-characters-by-frequency/)
- [659. 分割数组为连续子序列](https://leetcode-cn.com/problems/split-array-into-consecutive-subsequences/)---------------------------------[详细题解地址](https://www.acwing.com/solution/content/4896/)
- [692. 前K个高频单词](https://leetcode-cn.com/problems/top-k-frequent-words/)
- [973. 最接近原点的 K 个点](https://leetcode-cn.com/problems/k-closest-points-to-origin/)
堆(特征:第K个数)
priority_queue<T> q;// 默认大根堆
定义小根堆: priority_queue<T,vector<T>,greater<T>> q;
哈希表(特征:计数)
unordered_map<int,int> hash;
347. 前 K 个高频元素
215. 数组中的第K个最大元素
451. 根据字符出现频率排序
659. 分割数组为连续子序列---------------------------------详细题解地址
692. 前K个高频单词
要保证 次数是降序, 字母顺序是升序,而pair是双关键字排序,可以通过对 次数取负数来实现相同的排序顺序。
启发:有时候对关键字取负数 ,大根堆就变成小根堆了。
typedef pair<int,string> PIS;
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string,int> cnt;
for(auto &c : words) cnt[c] ++;
priority_queue<PIS> heap;
for(auto &c : cnt)
{
heap.push({-c.second,c.first}); // 大根堆,相反数,次数越多沉到越底下
if(heap.size() > k) heap.pop();
}
//vector<string> res;
// while(heap.size())
// {
// auto t = heap.top();
// heap.pop();
// res.push_back(t.second);
// }
// reverse(res.begin(),res.end()); // 按字典序排序
// 或者直接开k个空间,倒着排
vector<string> res(k);
for(int i = k -1;i >= 0 ;i --)
{
res[i] = heap.top().second;
heap.pop();
}
return res;
}
};