题目描述
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]
Example 2:
Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2
Output: [1,1],[1,1]
Explanation: 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:
Input: nums1 = [1,2], nums2 = [3], k = 3
Output: [1,3],[2,3]
Explanation: All possible pairs are returned from the sequence: [1,3],[2,3]
算法1
(Greedy) $O(n^2)$
在candidates中选出和最小的数对,将其index向右推进一步,重复操作k次,得到最小的k个数对。用重新定义的priority_queue取得最小的数对和,vector[HTML_REMOVED]中存放{nums1[i],nums2[j],j},每次操作j++将nums2中的数右移一位。
时间复杂度
O(n1+klogk)
space O(k);
参考文献
C++ 代码
struct comp{
bool operator()(vector<int> &a, vector<int>&b)
{
return a[0]+a[1]>b[0]+b[1]||(a[0]+a[1]==b[0]+b[1] && a[2]>b[2]);
}
};
class Solution {
public:
vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
int n1=nums1.size(), n2=nums2.size();
if(n1==0 || n2==0) return {};
vector<vector<int>> res;
priority_queue<vector<int>, vector<vector<int>>, comp> q;
for(int k=0;k<n1;k++)
{
q.push({nums1[k], nums2[0], 0});
}
while(k-- && !q.empty())
{
auto t=q.top(); q.pop();
res.push_back({t[0],t[1]});
int idx=t[2];
if(idx<n2-1)
{
idx++;
q.push({t[0],nums2[idx], idx});
}
}
return res;
}
};
/*
nums1 = [1,7,11],
nums2 = [2,4,6], k = 3
1,2,0 0->1 1,4,1 1->2 1,6,2
7,2,0
11,2,0
*/