#373
Medium
auto_awesome

LeetCode 题解工作台

查找和最小的 K 对数字

给定两个以 非递减顺序排列 的整数数组 nums1 和 nums2 , 以及一个整数 k 。 定义一对值 (u,v) ,其中第一个元素来自 nums1 ,第二个元素来自 nums2 。 请找到和最小的 k 个数对 (u 1 ,v 1 ) , (u 2 ,v 2 ) ... (u k ,v k ) 。…

category

2

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

中等 ·

bolt

答案摘要

class Solution: def kSmallestPairs(

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 堆 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定两个以 非递减顺序排列 的整数数组 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] <= 109
  • nums1nums2 均为 升序排列
  • 1 <= k <= 104
  • k <= nums1.length * nums2.length
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
speed

复杂度分析

指标
时间O(\min(k \cdot \log k, m \cdot n \cdot \log (m \cdot n)))
空间O(\min(k, m \cdot n))
psychology

面试官常问的追问

外企场景
  • 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?

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

查找和最小的 K 对数字题解:堆 | LeetCode #373 中等