LC373. 查找和最小的 K 对数字

LC373. 查找和最小的 K 对数字

给定两个以 非递减顺序排列 的整数数组 nums1nums2 , 以及一个整数 k

定义一对值 (u,v),其中第一个元素来自 nums1,第二个元素来自 nums2

请找到和最小的 k 个数对 (u1,v1), (u2,v2) ... (uk,vk)

示例 1:

1
2
3
4
输入: nums1 = [1,7,11], nums2 = [2,4,6], k = 3
输出: [1,2],[1,4],[1,6]
解释: 返回序列中的前 3 对数:
[1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]

示例 2:

1
2
3
4
输入: nums1 = [1,1,2], nums2 = [1,2,3], k = 2
输出: [1,1],[1,1]
解释: 返回序列中的前 2 对数:
[1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]

提示:

  • 1 <= nums1.length, nums2.length <= 105
  • -109 <= nums1[i], nums2[i] <= 109
  • nums1nums2 均为 升序排列
  • 1 <= k <= 104
  • k <= nums1.length * nums2.length
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
auto cmp = [](const vector<int>& a, const vector<int>& b){return (a[0] + a[1]) > (b[0] + b[1]);};
priority_queue<vector<int>, vector<vector<int>>, decltype(cmp)> pq(cmp);

for(int i = 0; i < nums1.size(); i++) {
pq.push({nums1[i], nums2[0], 0});
}

vector<vector<int>> res;
while(!pq.empty() && k > 0) {
vector<int> cur = pq.top();
pq.pop();
k--;

int next_index = cur[2] + 1;
if(next_index < nums2.size()) {
pq.push({cur[0], nums2[next_index], next_index});
}

res.push_back({cur[0], cur[1]});
}
return res;
}
};

LC373. 查找和最小的 K 对数字
http://binbo-zappy.github.io/2025/03/04/leetcode/LC373-查找和最小的 K 对数字/
作者
Binbo
发布于
2025年3月4日
许可协议