[LC] 373. Find K Pairs with Smallest Sums
2024-09-07 06:06:42
You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.
Define a pair (u,v) which consists of one element from the first array and one element from the second array.
Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) with the smallest sums.
Example 1:
Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3
Output: [[1,2],[1,4],[1,6]]
Explanation: The first 3 pairs are returned from the sequence:
[1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]
class Solution {
public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
List<List<Integer>> res = new ArrayList<>();
if (nums1.length == 0 || nums2.length == 0 || k == 0) {
return res;
}
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] + a[1] - b[0] - b[1]);
for (int i = 0; i < nums1.length && i < k; i++) {
pq.offer(new int[]{nums1[i], nums2[0], 0});
} while (!pq.isEmpty() && k-- > 0) {
int[] cur = pq.poll();
res.add(Arrays.asList(cur[0], cur[1]));
if (cur[2] == nums2.length - 1) {
continue;
}
pq.offer(new int[]{cur[0], nums2[cur[2] + 1], cur[2] + 1});
}
return res;
}
}
最新文章
- df 命令(转)
- iOS - Swift NSNumber		数字
- Unieap3.5Java端通过SQL语句直接查询DataStore
- 【转】eclipse怎么设置字体大小
- python学习第六天
- codeforces C. No to Palindromes!
- SemaphoreFullException when checking user role via ASP.NET membership
- PCRE兼容正则表达式函数
- outlook gmail setting
- .net core CLI(创建VueJS||Angular结合的项目)
- 2018-11-06 Visual Studio Code插件-英汉词典初版发布
- Mysql: Specified key was too long; max key length is 1000 bytes
- python set集合一些基本方法
- Java多线程学习笔记之三内存屏障与Java内存模型
- C#使用WebService 常见问题处理
- Effective C++:条款26:尽可能延后变量定义式的出现时间
- kubernetes 示例 hello world
- WEB基础技术(汇聚页)
- scala学习笔记(9): 语法续
- 【应用】wamp3.x.x设置,让外网能够访问本服务器
热门文章
- Ansible常见错误解析
- c++ 模板练习2
- 题解 Luogu P2499: [SDOI2012]象棋
- CTF-域渗透--HTTP服务--命令注入2
- Vue-router(4)之路由跳转
- one_day_one_linuxCmd---netstat命令
- linux tar/ tar.gz文件解压
- ZJNU 2340/2341/2343 - 罗小黑的“礼物”Ⅰ/Ⅱ/Ⅲ
- Docker MongoDB 集群搭建
- Lyft、Uber、滴滴涉足汽车租赁领域,能打破既有汽车所有权模式吗?