当前位置:网站首页>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;
}
};
边栏推荐
- [rust web rokcet Series 2] connect the database and add, delete, modify and check curd
- [技术发展-21]:网络与通信技术的应用与发展快速概览-1- 互联网网络技术
- Matlab uses resample to complete resampling
- 大学的知识是否学而无用、过时?
- 城市选择器组件实现原理
- SQLite 3 of embedded database
- 微信小程序中使用tabBar
- Game thinking 15: thinking about the whole region and sub region Services
- What are the skills of spot gold analysis?
- 6-2 vulnerability exploitation - inevitable problems of FTP
猜你喜欢

Selection of field types for creating tables in MySQL database

Quatre stratégies de base pour migrer la charge de travail de l'informatique en nuage

开发工具创新升级,鲲鹏推进计算产业“竹林”式生长

成功实现边缘编码需要了解的六大经验教训

Introduction to ffmpeg Lib

mysql列转行函数指的是什么

What are the skills of spot gold analysis?

Implementation of Weibo system based on SSM

跨域?同源?一次搞懂什么是跨域

人工智能在网络安全中的作用
随机推荐
The difference between new and malloc
SQLite 3 of embedded database
Introduction to ffmpeg Lib
Raspberry pie 4B learning notes - IO communication (1-wire)
[rust web rokcet Series 1] Hello, world and get, post, put, delete
Altium designer measure distance (ctrl+m)
Leetcode, 3 repeatless longest subsequence
Penser au jeu 15: penser au service complet et au sous - service
I Brief introduction of radio energy transmission technology
Self drawing of menu items and CListBox items
Six lessons to be learned for the successful implementation of edge coding
Using tabbar in wechat applet
Unity AssetBundle subcontracting
Android: the kotlin language uses grendao3, a cross platform app development framework
1069. Division of convex polygons (thinking, interval DP)
人工智能在网络安全中的作用
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
This is the report that leaders like! Learn dynamic visual charts, promotion and salary increase are indispensable
SAP ui5 beginner tutorial 20 - explanation of expression binding usage of SAP ui5
【视频】马尔可夫链蒙特卡罗方法MCMC原理与R语言实现|数据分享