当前位置:网站首页>leetcode373. 查找和最小的 K 对数字(中等)
leetcode373. 查找和最小的 K 对数字(中等)
2022-07-02 01:51:00 【重you小垃】



同 leetcode378.有序矩阵中第K小的元素(中等) 类似
https://blog.csdn.net/zhangjiaji111/article/details/122716718
思路:归并排序
刚开始错误的思路:先把v1[0]v2[0]放进去,然后获得v1[x] v2[y]如果将 v1[x+1] v2[y]和v1[x] v2[y+1]放入的话会出现重复!
正解:先将[0…min(k,n-1)][0]放进去,每次拿到v1[x]v2[y]将v1[x]v2[y+1]放入
class Solution {
public:
struct cmp{
bool operator()(vector<int>& v1, vector<int>& v2) {
return v1[0] + v1[1] > v2[0] + v2[1];
}
};
vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
vector<vector<int>> ans;
priority_queue<vector<int>, vector<vector<int>>, cmp> pq;
int n = nums1.size(), m = nums2.size();
for (int i = 0; i < min(k, n); ++i) {
pq.push(vector<int>{
nums1[i], nums2[0], i, 0});
}
while (k > 0) {
if(pq.empty()) break;
auto tp = pq.top();
pq.pop();
ans.push_back(vector<int>{
tp[0], tp[1]});
if (tp[3] < m - 1) pq.push(vector<int>{
nums1[tp[2]],nums2[tp[3]+1],tp[2],tp[3]+1});
k--;
}
return ans;
}
};
边栏推荐
- This is the report that leaders like! Learn dynamic visual charts, promotion and salary increase are indispensable
- 人工智能在网络安全中的作用
- 如何用一款产品推动「品牌的惊险一跃」?
- New news, Wuhan Yangluo international port, filled with black technology, refreshes your understanding of the port
- 【视频】马尔可夫链原理可视化解释与R语言区制转换MRS实例|数据分享
- Automatically browse pinduoduo products
- 牛客网——华为题库(51~60)
- PR second training
- Redis有序集合如何使用
- 成功实现边缘编码需要了解的六大经验教训
猜你喜欢

Android: how can golden nine and silver ten squeeze into the first-line big factories from small and medium-sized enterprises? The depth of interview questions in large factories

人工智能在网络安全中的作用

PR second training

企业应该选择无服务器计算吗?

The concept, function, characteristics, creation and deletion of MySQL constraints

mysql列转行函数指的是什么

医药管理系统(大一下C语言课设)

MySQL如何解决delete大量数据后空间不释放的问题

With the innovation and upgrading of development tools, Kunpeng promotes the "bamboo forest" growth of the computing industry

如何用一款产品推动「品牌的惊险一跃」?
随机推荐
Implementation principle of city selector component
大学的知识是否学而无用、过时?
Parted command
迁移云计算工作负载的四个基本策略
基于SSM实现微博系统
Architecture evolution from MVC to DDD
C language 3-7 daffodils (enhanced version)
Experimental reproduction of variable image compression with a scale hyperprior
How to use a product to promote "brand thrill"?
并发编程的三大核心问题
Ubuntu20.04 PostgreSQL 14 installation configuration record
II Basic structure of radio energy transmission system
This is the form of the K-line diagram (pithy formula)
Feature extraction and detection 16 brisk feature detection and matching
城市选择器组件实现原理
MySQL view concept, create view, view, modify view, delete view
企业应该选择无服务器计算吗?
2022 Q2 - 提升技能的技巧总结
new和malloc的区别
I Brief introduction of radio energy transmission technology