剑指 Offer II 堆
2024-10-20 18:52:02
059. 数据流的第 K 大数值
class KthLargest {
public:
priority_queue<int,vector<int>,greater<int>>heap;//小根堆 维护第1大到第k大的数 top就是第k大的数
int k;//太妙了
/*
第n大 n-1 n-2 ... k k-1 k-2 ... 第1大
如果加的数小于a[k] 它将被弹走
大 k是第k+1大的 把k弹出去
*/
KthLargest(int _k, vector<int>& nums) {
k=_k;
for(auto x:nums)
{
heap.push(x);
if(heap.size()>k)heap.pop();
}
}
int add(int val) {
heap.push(val);
if(heap.size()>k)heap.pop();
return heap.top();
}
};
060. 出现频率最高的 k 个数字
class Solution {
public:
/*
计数排序
因为最多出现n次 拿一个数组存 出现i次元素的有多少个
*/
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int>cnt;//每个元素出现了多少次
int n=nums.size();
vector<int>ans;
vector<int>f(n+1);
for(auto x:nums)cnt[x]++;
for(auto [x,c]: cnt)f[c]++;
int i=n;
while(k>0)k-=f[i--];
for(auto [x,c]:cnt)
if(c>i)ans.push_back(x);
return ans;
}
};
061. 和最小的 k 个数对
class Solution {
typedef vector<int> VI;
/*
多路归并
b0+a0 b0+a1 +... + a[n-1]
b1
.
.
.
b[m-1]
优先队列 存vector<int> 不是int
*/
public:
vector<vector<int>> kSmallestPairs(vector<int>& a, vector<int>& b, int k) {
priority_queue<VI,vector<VI>,greater<VI>>heap;
vector<VI>ans;
int n=a.size(),m=b.size();
for(int i=0;i<m;i++)heap.push({b[i]+a[0],0,i});
// b[i]+a[0]用于比较
//0是a下标 i是b下标 用于传答案
while(heap.size()&&k)
{
k--;
VI t=heap.top();
heap.pop();
ans.push_back({a[t[1]],b[t[2]]});
if(t[1]+1<n)heap.push({a[t[1]+1]+b[t[2]],t[1]+1,t[2]});
}
return ans;
}
};
最新文章
- Python之路3【第一篇】Python基础
- PHP工作笔记:使用yii migrate管理、生成数据库
- google 火狐 模拟显示手机页面插件
- cxf client在后台不通且chunk设置为false的时候不能在控制台输出请求日志
- FZU 1894 志愿者选拔 (单调队列)
- poj1459 Power Network (多源多汇最大流)
- ThinkPHP之验证码的使用
- php延迟加载的示例
- NDIS IM 驱动那些事情
- ubuntu免验证登陆权限问题
- 最通用的ibatis.Net使用sql server存储过程返回分页数据的详细例子
- spring @Bean注解的使用
- this()基础用法
- P1197 [JSOI2008]星球大战 并查集 反向
- Guava之计时器Stopwatch
- JMeter学习(三十一)non-gui模式运行(转载)
- asp.net调用js方法
- Robolectric 单元测试中使用 Ressource
- orcale 之pl/sql例外
- iOS:GCD技术——仅仅执行一次和执行多次 dispatch_once和dispatch_apply