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.

这道题给了我们两个数组,让我们从每个数组中任意取出一个数字来组成不同的数字对,返回前K个和最小的数字对。那么这道题有多种解法,我们首先来看brute force的解法,这种方法我们从0循环到数组的个数和k之间的较小值,这样做的好处是如果k远小于数组个数时,我们不需要计算所有的数字对,而是最多计算k*k个数字对,然后将其都保存在res里,这时候我们给res排序,用我们自定义的比较器,就是和的比较,然后把比k多出的数字对删掉即可,参见代码如下:

解法一:

class Solution {
public:
vector<pair<int, int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
vector<pair<int, int>> res;
for (int i = ; i < min((int)nums1.size(), k); ++i) {
for (int j = ; j < min((int)nums2.size(), k); ++j) {
res.push_back({nums1[i], nums2[j]});
}
}
sort(res.begin(), res.end(), [](pair<int, int> &a, pair<int, int> &b){return a.first + a.second < b.first + b.second;});
if (res.size() > k) res.erase(res.begin() + k, res.end());
return res;
}
};

我们也可以使用multimap来做,思路是我们将数组对之和作为key存入multimap中,利用其自动排序的机制,这样我们就可以省去sort的步骤,最后把前k个存入res中即可:

解法二:

class Solution {
public:
vector<pair<int, int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
vector<pair<int, int>> res;
multimap<int, pair<int, int>> m;
for (int i = ; i < min((int)nums1.size(), k); ++i) {
for (int j = ; j < min((int)nums2.size(), k); ++j) {
m.insert({nums1[i] + nums2[j], {nums1[i], nums2[j]}});
}
}
for (auto it = m.begin(); it != m.end(); ++it) {
res.push_back(it->second);
if (--k <= ) return res;
}
return res;
}
};

下面这种方式用了priority_queue,也需要我们自定义比较器,整体思路和上面的没有什么区别:

解法三:

class Solution {
public:
vector<pair<int, int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
vector<pair<int, int>> res;
priority_queue<pair<int, int>, vector<pair<int, int>>, cmp> q;
for (int i = ; i < min((int)nums1.size(), k); ++i) {
for (int j = ; j < min((int)nums2.size(), k); ++j) {
if (q.size() < k) {
q.push({nums1[i], nums2[j]});
} else if (nums1[i] + nums2[j] < q.top().first + q.top().second) {
q.push({nums1[i], nums2[j]}); q.pop();
}
}
}
while (!q.empty()) {
res.push_back(q.top()); q.pop();
}
return res;
}
struct cmp {
bool operator() (pair<int, int> &a, pair<int, int> &b) {
return a.first + a.second < b.first + b.second;
}
};
};

下面这种方法比较另类,我们遍历nums1数组,对于nums1数组中的每一个数字,我们并不需要遍历nums2中所有的数字,实际上,对于nums1中的数字,我们只需要记录nums2中下一个可能组成数字对的坐标,这里我们使用一个idx数组,其中idx[i]表示的数字是nums1[i]将从nums2数组上开始寻找的位置,因为 {nums1[i], nums2[i - 1]} 已经被加入到了结果res中,这种方法其实也是一种地毯式搜索,但是并不需要遍历完所有的组合,因为我们有idx数组来进行剪枝。我们suppose需要进行k次循环,但是题目中没有说我们一定能取出k对数字,而我们能取出的对儿数跟数组nums1和nums2的长度有关,最多能取出二者的长度之积的对儿数,所以我们取其跟k之间的较小值为循环次数。我们定义idx数组,长度为nums1的长度,初始化均为0。下面开始循环,在每次循环中,我们新建变量cur,记录从nums1中取数的位置,初始化为0,使用变量sum来记录一个当前最小的两数之和,初始化为正无穷。然后开始遍历数组nums1,更新sum的条件有两个,第一个是idx[i]上的数要小于nums2的长度,因为其是在nums2开始寻找的位置,当然不能越界,第二个条件的候选的两个数组 nums1[i] 和 nums2[idx[i]] 之和小于等于sum。同时满足这两个条件就可以更新sum了,同时更新cur为i,表示当前从nums1取出数字的位置。当遍历nums1的for循环结束后,此时cur的位置就是要从nums1取出的数字的位置,根据idx[cur]从nums2中取出对应的数组,形成数对儿存入结果res中,然后idx[cur]自增1,因为当前位置的数字已经用过了,下次遍历直接从后面一个数字开始吧,这是本解法的设计精髓所在,一定要弄清楚idx数组的意义,参见代码如下:

解法四:

class Solution {
public:
vector<pair<int, int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
vector<pair<int, int>> res;
int size = min(k, int(nums1.size() * nums2.size()));
vector<int> idx(nums1.size(), );
for (int t = ; t < size; ++t) {
int cur = , sum = INT_MAX;
for (int i = ; i < nums1.size(); ++i) {
if (idx[i] < nums2.size() && sum >= nums1[i] + nums2[idx[i]]) {
cur = i;
sum = nums1[i] + nums2[idx[i]];
}
}
res.push_back({nums1[cur], nums2[idx[cur]]});
++idx[cur];
}
return res;
}
};

参考资料:

https://discuss.leetcode.com/topic/50429/c-solution

https://discuss.leetcode.com/topic/50459/c-idea-of-using-multimap

https://discuss.leetcode.com/topic/50422/naive-accepted-solution-c

https://discuss.leetcode.com/topic/50421/c-priority_queue-solution

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Find K Pairs with Smallest Sums 找和最小的K对数字的更多相关文章

  1. [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 ...

  2. 373 Find K Pairs with Smallest Sums 查找和最小的K对数字

    给定两个以升序排列的整形数组 nums1 和 nums2, 以及一个整数 k.定义一对值 (u,v),其中第一个元素来自 nums1,第二个元素来自 nums2.找到和最小的 k 对数字 (u1,v1 ...

  3. 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 ...

  4. 【LeetCode】373. Find K Pairs with Smallest Sums 解题报告(Python)

    [LeetCode]373. Find K Pairs with Smallest Sums 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/p ...

  5. 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 ...

  6. 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 ...

  7. #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 ...

  8. 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 ...

  9. 【leetcode】Find K Pairs with Smallest Sums

    You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k. Define ...

随机推荐

  1. 增强学习(三)----- MDP的动态规划解法

    上一篇我们已经说到了,增强学习的目的就是求解马尔可夫决策过程(MDP)的最优策略,使其在任意初始状态下,都能获得最大的Vπ值.(本文不考虑非马尔可夫环境和不完全可观测马尔可夫决策过程(POMDP)中的 ...

  2. 放弃安卓原生TimePicker,选择wheelView打造更漂亮的时间get,以及动态拉伸输入框布局,这些,这里都有!

    最近公司要求的上线项目有这么一个需求,要写一个请假申请的页面,里面必须有请假开始时间,结束时间,还有一个请假原因. 于是想到时间选择嘛,官方不是有个DatePicker吗?额,是不是要DatePick ...

  3. mailto实现将用户在网页中输入的内容传递到本地邮件客户端

    背景: 想在自己的网站中有这样一个设计: 用户点击提交按钮之后,就会打开本地邮件客户端,并自动将他在输入框中输入的内容作为邮件的内容,像下面这样: mailto可以帮助实现这个功能. 简介: mail ...

  4. 在CentOS或RHEL上安装Nux Dextop仓库

    介绍 Nux Dextop是类似CentOS.RHEL.ScientificLinux的第三方RPM仓库(比如:Ardour,Shutter等等).目前,Nux Dextop对CentOS/RHEL ...

  5. [Q&A] C1DataGrid 奇葩的 BeginNewRow() 方法

    一.前言 用户千千万,自然需求就千奇百怪都有,某天有人提了这样一个需求: 某个 C1DataGrid 在 ScrollViewer 的底部(使纵向滚动条显示出来),然后当该 C1DataGrid 增加 ...

  6. 使用BitArray判断素数

    首先显示1024范围内的所有素数,然后显示输入的数是否是素数.1024 是代码中计算的素数的范围,可以修改.计算平方根,是为了确定一个基数的范围.1024的平方根是32,两个超过32 的数相乘,肯定大 ...

  7. 【转】ZigBee终端入网方式深入分析

    前述 继之前对终端Direct Join的分析,发现很多东西还很模糊,存在很多问题.终于找到时间继续深入挖下去,这次应该比较完整地搞清了终端的入网机制,并纠正之前的几个认识偏差. 由于Z-Stack网 ...

  8. Java工程师成神之路

    学习Java的同学注意了!!! 学习过程中遇到什么问题或者想获取学习资源的话,欢迎加入Java学习交流群,群号码:279558494 我们一起学Java! 一.基础篇 1.1 JVM 1.1.1. J ...

  9. MongoDB进行MapReduce的数据类型

    有很长一段时间没更新博客了,因为最近都比较忙,今天算是有点空闲吧.本文主要是介绍MapReduce在MongoDB上的使用,它与sql的分组.聚集类似,也是先map分组,再用reduce统计,最后还可 ...

  10. json简单使用

    web工程中如何将大量数据从服务器端传送到浏览器一直是很重要的一个问题. 其中一个解决方法是在服务器端将将数据封装成json格式,然后传给前台.废话不多说,下面讲干货. 1.要用json必须下载一个库 ...