[LeetCode] 373. Find K Pairs with Smallest Sums 找和最小的K对数字
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:
Given nums1 = [1,7,11], nums2 = [2,4,6], k = 3 Return: [1,2],[1,4],[1,6] 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]
Example 2:
Given nums1 = [1,1,2], nums2 = [1,2,3], k = 2 Return: [1,1],[1,1] The first 2 pairs are returned from the sequence:
[1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]
Example 3:
Given nums1 = [1,2], nums2 = [3], k = 3 Return: [1,3],[2,3] All possible pairs are returned from the sequence:
[1,3],[2,3]
Credits:
Special thanks to @elmirap and @StefanPochmann for adding this problem and creating all test cases.
给定2个以升序排列的整数数组和1个整数k,从2个数组中各拿出一个数字组成一对,找出k对和最小的数字组合。
解法1:最简单的想法就是暴力brute force解法,但效率肯定不高。
解法2: 最小堆。把所有的点对加入到最小堆,然后输出前k个。但没有利用到“两个数组都有序”这个条件,就算数组无序,也可以利用这个方法。要利用有序这个条件,可以借助mergesort的思路,pair的第一个元素至多包含了nums1数组的前k个元素,k以后的可以不用考虑。所以,这形成了k个list,每一个list都包含了nums2的元素。每一次取所有list中的最小值,然后该list下一个元素入队。
Java:
public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {
List<int[]> r = new ArrayList<>();
if(nums1.length == 0 || nums2.length == 0) return r;
int size = Math.min(nums1.length, k);
int[] index = new int[size];
PriorityQueue<int[]> queue = new PriorityQueue<>(new Comparator<int[]>(){
@Override
public int compare(int[] o1, int[] o2) {
Integer s1 = o1[0] + o1[1];
Integer s2 = o2[0] + o2[1];
return s1.compareTo(s2);
}
});
for(int i = 0; i < size; i++){
queue.add(new int[]{nums1[i], nums2[0], i});
}
int count = 0;
while(!queue.isEmpty()){
int[] pair = queue.poll();
r.add(new int[]{pair[0], pair[1]});
int id = pair[2];
if(++index[id] < nums2.length)
queue.add(new int[]{nums1[id], nums2[index[id]], id});
count++;
if(count == k)
break;
}
return r;
}
Python:
from heapq import heappush, heappop class Solution(object):
def kSmallestPairs(self, nums1, nums2, k):
"""
:type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: List[List[int]]
"""
pairs = []
if len(nums1) > len(nums2):
tmp = self.kSmallestPairs(nums2, nums1, k)
for pair in tmp:
pairs.append([pair[1], pair[0]])
return pairs min_heap = []
def push(i, j):
if i < len(nums1) and j < len(nums2):
heappush(min_heap, [nums1[i] + nums2[j], i, j]) push(0, 0)
while min_heap and len(pairs) < k:
_, i, j = heappop(min_heap)
pairs.append([nums1[i], nums2[j]])
push(i, j + 1)
if j == 0:
push(i + 1, 0) # at most queue min(n, m) space
return pairs
C++:
// Time: O(k * log(min(n, m, k))), where n is the size of num1, and m is the size of num2.
// Space: O(min(n, m, k)) class Solution {
public:
vector<pair<int, int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
vector<pair<int, int>> pairs;
if (nums1.size() > nums2.size()) {
vector<pair<int, int>> tmp = kSmallestPairs(nums2, nums1, k);
for (const auto& pair : tmp) {
pairs.emplace_back(pair.second, pair.first);
}
return pairs;
} using P = pair<int, pair<int, int>>;
priority_queue<P, vector<P>, greater<P>> q;
auto push = [&nums1, &nums2, &q](int i, int j) {
if (i < nums1.size() && j < nums2.size()) {
q.emplace(nums1[i] + nums2[j], make_pair(i, j));
}
}; push(0, 0);
while (!q.empty() && pairs.size() < k) {
auto tmp = q.top(); q.pop();
int i, j;
tie(i, j) = tmp.second;
pairs.emplace_back(nums1[i], nums2[j]);
push(i, j + 1);
if (j == 0) {
push(i + 1, 0); // at most queue min(m, n) space.
}
}
return pairs;
}
};
All LeetCode Questions List 题目汇总
[LeetCode] 373. Find K Pairs with Smallest Sums 找和最小的K对数字的更多相关文章
- [LeetCode] Find K Pairs with Smallest Sums 找和最小的K对数字
You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k. Define ...
- 373 Find K Pairs with Smallest Sums 查找和最小的K对数字
给定两个以升序排列的整形数组 nums1 和 nums2, 以及一个整数 k.定义一对值 (u,v),其中第一个元素来自 nums1,第二个元素来自 nums2.找到和最小的 k 对数字 (u1,v1 ...
- 373. Find K Pairs with Smallest Sums 找出求和和最小的k组数
[抄题]: You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k. D ...
- 【LeetCode】373. Find K Pairs with Smallest Sums 解题报告(Python)
[LeetCode]373. Find K Pairs with Smallest Sums 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/p ...
- 373. Find K Pairs with Smallest Sums
You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k. 给你两个数组n ...
- 373. Find K Pairs with Smallest Sums (java,优先队列)
题目: You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k. Def ...
- #Leetcode# 373. Find K Pairs with Smallest Sums
https://leetcode.com/problems/find-k-pairs-with-smallest-sums/ You are given two integer arrays nums ...
- Leetcode Find K Pairs with smallest sums
本题的特点在于两个list nums1和nums2都是已经排序好的.本题如果把所有的(i, j)组合都排序出来,再取其中最小的K个.其实靠后的很多组合根本用不到,所以效率较低,会导致算法超时.为了简便 ...
- Find K Pairs with Smallest Sums -- LeetCode
You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k. Define ...
随机推荐
- TCP/IP超详细总结
网络的基础知识 一.协议 1.简介: 在计算机网络与信息通信领域里,人们经常提及“协议”一词.互联网中常用的具有代表性的协议有IP.TCP.HTTP等.而LAN(局域网)中常用的协议有IPX/SPX” ...
- 洛谷P3402 可持久化并查集
n个集合 m个操作 操作: 1 a b 合并a,b所在集合 2 k 回到第k次操作之后的状态(查询算作操作) 3 a b 询问a,b是否属于同一集合,是则输出1否则输出0 说是可持久化并查集,实际上是 ...
- 【hiho1715】树的联通问题
题目大意:给定一棵 1~n 标号的树.Tree[L,R]表示最少需要选择的边的数量使得 L~R 号点两两连通.求: \[ \sum_{L=1}^{n} \sum_{R=L}^{n} \operator ...
- 细数meta标签的奥秘
因为看到了一个很不错的h5自适应网站,觉得很不错,于是好奇心作祟,让我翻开了它的源码一探究竟,最先研究的是它的meta标签,好了,废话不多说,以下是我总结的和比较实用的meta标签,如有错误,请多多指 ...
- 胡昊—第6次作业—static关键字、对象
#题目1:编写一个类Computer,类中含有一个求n的阶乘的方法.将该类打包,并在另一包中的Java文件App.java中引入包,在主类中定义Computer类的对象,调用求n的阶乘的方法(n值由参 ...
- python算数、逻辑运算,位运算
算术运算符 对变量和数组进行算术运算. 算术运算符:+,-,*,/,% +:将连个或者多个数值相加 -:将两个数值相减 *:将两个数值相乘 /:将两个数值相除 %:取相除的余数 赋值运算符 将右边的值 ...
- 利用docker 部署项目
docker_tomcat_jdk 7.0 1.6 app admin && api 1.yum install docker 2.service docker start 3.创建文 ...
- 【NOIP2017提高A组模拟10.7】Adore
题目 小w 偶然间见到了一个DAG. 这个DAG 有m 层,第一层只有一个源点,最后一层只有一个汇点,剩下的每一层都有k 个节点. 现在小w 每次可以取反第i(1 < i < n - 1) ...
- 织梦M手机端/自适应网站内容图片变形解决办法
我们在做响应式网站或者织梦M功能手机站的时候,会发现如果内容页图片太大,在移动端显示会变形,dede手机端图片过长等问题,手机端文章内容页图片不能自适应!这给通过手机端浏览网站的用户造成了很不好的用户 ...
- JS实现 Tab栏切换案例
要求:当鼠标点击上面相应的选项卡(tab),下面页面的内容也随之而改变. 结构分析: 全部的内容都放到一个大的盒子里面,盒子里面又可以分为上面和下面两个盒子. 上面的盒子放了 5个li,装着5个小的选 ...