小顶堆
class KthLargest {
public:
int k = 0;
priority_queue<int,vector<int>,greater<int>> heap;
KthLargest(int k, vector<int>& nums) {
for(int num: nums) heap.push(num);
this->k = k;
}
int add(int val) {
heap.push(val);
while(heap.size() > k) heap.pop();
return heap.top();
}
};
剑指 Offer II 060. 出现频率最高的 k 个数字
方法一、使用哈希表记录次数,然后遍历哈希表让堆来维护前 k k k 大,时间复杂度就为 O ( N l o g k ) O(Nlogk) O(Nlogk) 。
class Solution {
public:
typedef pair<int,int> PII;
unordered_map<int,int> cnts;
static bool cmp(const PII &a, const PII &b) {
return a.second > b.second;
}
vector<int> topKFrequent(vector<int>& nums, int k) {
for(int num: nums) {
cnts[num]++;
}
//自定义排序规则
priority_queue<PII,vector<PII>,decltype(&cmp)> heap(cmp);
for(auto p: cnts) {
if(heap.size() == k) { //保持堆大小不大于k
if(heap.top().second < p.second) {
heap.pop();
heap.emplace(p);
}
} else heap.emplace(p);
}
vector<int> res;
while(heap.size()) {
res.emplace_back(heap.top().first);
heap.pop();
}
return res;
}
};
方法二、使用哈希表记录次数,然后再排序取出前k大的数即可。时间 O ( N l o g N ) O(NlogN) O(NlogN)
class Solution {
public:
unordered_map<int,int> cnts;
static bool cmp(const pair<int,int> &a, const pair<int,int> &b) {
return a.second > b.second;
}
vector<int> topKFrequent(vector<int>& nums, int k) {
int maxx = 0;
for(int num: nums) {
cnts[num]++;
}
vector<pair<int,int>> ls;
for(auto p: cnts) {
ls.emplace_back(p);
}
sort(ls.begin(),ls.end(),cmp);
ls.erase(ls.begin()+k,ls.end());
vector<int> res;
for(auto num: ls) res.emplace_back(num.first);
return res;
}
};
class Solution {
public:
typedef pair<int,int> PII;
vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
auto cmp = [&nums1,&nums2](const PII &a, const PII &b) {
return nums1[a.first]+nums2[a.second] > nums1[b.first]+nums2[b.second];
};
int n = nums1.size();
int m = nums2.size();
priority_queue<PII,vector<PII>,decltype(cmp)> heap(cmp);
for(int i = 0; i < min(k,n); i++) {
heap.emplace(i,0);
}
vector<vector<int>> res;
while(k-- && heap.size()) {
auto [x,y] = heap.top();
heap.pop();
res.push_back({nums1[x],nums2[y]});
if(y+1 < m) heap.emplace(x,y+1);
}
return res;
}
};
参考:https://leetcode.cn/problems/qn8gGX/solution/he-zui-xiao-de-k-ge-shu-dui-by-leetcode-eoce6/