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.
vector<pair<int, int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
typedef pair<int,pair<int,int>> type;
priority_queue<type, vector<type>, greater<type>> que;
vector<pair<int,int>> res;
unordered_set<long long> uset;
que.emplace(make_pair(nums1.front() + nums2.front(), make_pair(0, 0)));
for (int i = 0; i < k && !queue.empty(); ++i) {
auto e = que.top();
que.pop();
int idx1 = e.second.first;
int idx2 = e.second.second;
res.emplace_back(make_pair(nums1[idx1], nums2[idx2]));
if (idx1 + 1 < nums1.size()) {
que.emplace(make_pair(nums1[idx1 + 1] + nums2[idx2], make_pair(idx1 + 1, idx2)));
}
if (idx1 == 0 && idx2 + 1 < nums2.size()) {
que.emplace(make_pair(nums1[idx1] + nums2[idx2 + 1], make_pair(idx1, idx2 + 1)));
}
}
return res;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。