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;
}
};

最新文章

  1. Python之路3【第一篇】Python基础
  2. PHP工作笔记:使用yii migrate管理、生成数据库
  3. google 火狐 模拟显示手机页面插件
  4. cxf client在后台不通且chunk设置为false的时候不能在控制台输出请求日志
  5. FZU 1894 志愿者选拔 (单调队列)
  6. poj1459 Power Network (多源多汇最大流)
  7. ThinkPHP之验证码的使用
  8. php延迟加载的示例
  9. NDIS IM 驱动那些事情
  10. ubuntu免验证登陆权限问题
  11. 最通用的ibatis.Net使用sql server存储过程返回分页数据的详细例子
  12. spring @Bean注解的使用
  13. this()基础用法
  14. P1197 [JSOI2008]星球大战 并查集 反向
  15. Guava之计时器Stopwatch
  16. JMeter学习(三十一)non-gui模式运行(转载)
  17. asp.net调用js方法
  18. Robolectric 单元测试中使用 Ressource
  19. orcale 之pl/sql例外
  20. iOS:GCD技术——仅仅执行一次和执行多次 dispatch_once和dispatch_apply

热门文章

  1. 《Terraform 101 从入门到实践》 Terraform在公有云Azure上的应用
  2. noip2020模拟赛 背包 (knapsack)
  3. 教你快速做一个自己的“ChatGPT”
  4. 跳板攻击之:dns2tcp
  5. 基于GLFW的PyOpenGL的使用
  6. 2023.3.4Leecode982按位与为零的三元组
  7. K8s集群调度
  8. 时间序列分析 2.X 单位根检验
  9. Unity ARCore动态增加识别图
  10. 对Frobenius 范数的理解