LeetCode 题解工作台
查找和最小的 K 对数字
给定两个以 非递减顺序排列 的整数数组 nums1 和 nums2 , 以及一个整数 k 。 定义一对值 (u,v) ,其中第一个元素来自 nums1 ,第二个元素来自 nums2 。 请找到和最小的 k 个数对 (u 1 ,v 1 ) , (u 2 ,v 2 ) ... (u k ,v k ) 。…
2
题型
4
代码语言
3
相关题
当前训练重点
中等 · 堆
答案摘要
class Solution: def kSmallestPairs(
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 堆 题型思路
题目描述
给定两个以 非递减顺序排列 的整数数组 nums1 和 nums2 , 以及一个整数 k 。
定义一对值 (u,v),其中第一个元素来自 nums1,第二个元素来自 nums2 。
请找到和最小的 k 个数对 (u1,v1), (u2,v2) ... (uk,vk) 。
示例 1:
输入: 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:
输入: 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] <= 109nums1和nums2均为 升序排列1 <= k <= 104k <= nums1.length * nums2.length
解题思路
方法一
class Solution:
def kSmallestPairs(
self, nums1: List[int], nums2: List[int], k: int
) -> List[List[int]]:
q = [[u + nums2[0], i, 0] for i, u in enumerate(nums1[:k])]
heapify(q)
ans = []
while q and k > 0:
_, i, j = heappop(q)
ans.append([nums1[i], nums2[j]])
k -= 1
if j + 1 < len(nums2):
heappush(q, [nums1[i] + nums2[j + 1], i, j + 1])
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(\min(k \cdot \log k, m \cdot n \cdot \log (m \cdot n))) |
| 空间 | O(\min(k, m \cdot n)) |
面试官常问的追问
外企场景- question_mark
Can the candidate efficiently combine array traversal with heap operations?
- question_mark
How well does the candidate manage the heap size and limit unnecessary operations?
- question_mark
Does the candidate understand the trade-off between time and space complexity in heap-based solutions?
常见陷阱
外企场景- error
Overpopulating the heap with all possible pairs instead of strategically pushing only potential candidates.
- error
Incorrectly handling the heap extraction order or failing to manage heap transitions between pairs.
- error
Failing to account for the sorted nature of the arrays, which can optimize the pairing strategy.
进阶变体
外企场景- arrow_right_alt
What if the arrays are unsorted? This would require sorting the arrays first before applying the heap method.
- arrow_right_alt
What if k exceeds the possible pairs from the arrays? In such cases, ensure the solution handles this scenario gracefully by limiting the output to the available pairs.
- arrow_right_alt
Handling arrays with duplicate elements. The solution should still work and return the correct k smallest sums, regardless of duplicates.