当前位置:网站首页>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;
}
};
边栏推荐
- JMeter (II) - install the custom thread groups plug-in
- MySQL如何解决delete大量数据后空间不释放的问题
- 游戏思考15:全区全服和分区分服的思考
- Matlab uses resample to complete resampling
- What are the skills of spot gold analysis?
- 2022 Q2 - Summary of skills to improve skills
- 跨域?同源?一次搞懂什么是跨域
- matlab 使用 audiorecorder、recordblocking录制声音,play 播放声音,audiowrite 保存声音
- np.where 和 torch.where 用法
- 遷移雲計算工作負載的四個基本策略
猜你喜欢
What is AQS and its principle
With the innovation and upgrading of development tools, Kunpeng promotes the "bamboo forest" growth of the computing industry
Réseau neuronal convolutif (y compris le Code et l'illustration correspondante)
What are the skills of spot gold analysis?
TSINGSEE青犀平台如何实现同一节点同时播放多个视频?
开发工具创新升级,鲲鹏推进计算产业“竹林”式生长
机器学习基本概念
1222. Password dropping (interval DP, bracket matching)
Discussion on the idea of platform construction
跨域?同源?一次搞懂什么是跨域
随机推荐
正则表达式学习笔记
This is the report that leaders like! Learn dynamic visual charts, promotion and salary increase are indispensable
Architecture evolution from MVC to DDD
Discussion on the idea of platform construction
The concept, function, characteristics, creation and deletion of MySQL constraints
Ks006 student achievement management system based on SSM
Ubuntu20.04 PostgreSQL 14 installation configuration record
Implementation of Weibo system based on SSM
2022 Q2 - 提昇技能的技巧總結
matlab 使用 resample 完成重采样
微信小程序中使用tabBar
Develop those things: how to use go singleton mode to ensure the security of high concurrency of streaming media?
np.where 和 torch.where 用法
np. Where and torch Where usage
Ubuntu20.04 PostgreSQL 14 installation configuration record
new和malloc的区别
C language 3-7 daffodils (enhanced version)
Parted command
开发那些事儿:如何利用Go单例模式保障流媒体高并发的安全性?
Laravel artisan 常用命令