LeetCode 题解工作台
有序矩阵中的第 k 个最小数组和
给你一个 m * n 的矩阵 mat ,以及一个整数 k ,矩阵中的每一行都以非递减的顺序排列。 你可以从每一行中选出 1 个元素形成一个数组。返回所有可能数组中的第 k 个 最小 数组和。 示例 1: 输入: mat = [[1,3,11],[2,4,6]], k = 5 输出: 7 解释: 从每…
4
题型
5
代码语言
3
相关题
当前训练重点
困难 · 二分·搜索·答案·空间
答案摘要
根据题目描述,我们需要找出前 行的所有可能数组中的第 个最小数组和。 如果我们能够找出前 $m - 1$ 行的所有可能数组中的前 个最小数组和,那么我们可以将第 行的每个元素与前 $m - 1$ 行的前 个最小数组和相加,将得到的所有结果排序后,取前 个最小值,即为前 行的所有可能数组中的前 个最小值。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
给你一个 m * n 的矩阵 mat,以及一个整数 k ,矩阵中的每一行都以非递减的顺序排列。
你可以从每一行中选出 1 个元素形成一个数组。返回所有可能数组中的第 k 个 最小 数组和。
示例 1:
输入:mat = [[1,3,11],[2,4,6]], k = 5 输出:7 解释:从每一行中选出一个元素,前 k 个和最小的数组分别是: [1,2], [1,4], [3,2], [3,4], [1,6]。其中第 5 个的和是 7 。
示例 2:
输入:mat = [[1,3,11],[2,4,6]], k = 9 输出:17
示例 3:
输入:mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7 输出:9 解释:从每一行中选出一个元素,前 k 个和最小的数组分别是: [1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]。其中第 7 个的和是 9 。
示例 4:
输入:mat = [[1,1,10],[2,2,9]], k = 7 输出:12
提示:
m == mat.lengthn == mat.length[i]1 <= m, n <= 401 <= k <= min(200, n ^ m)1 <= mat[i][j] <= 5000mat[i]是一个非递减数组
解题思路
方法一:逐行遍历 + 排序
根据题目描述,我们需要找出前 行的所有可能数组中的第 个最小数组和。
如果我们能够找出前 行的所有可能数组中的前 个最小数组和,那么我们可以将第 行的每个元素与前 行的前 个最小数组和相加,将得到的所有结果排序后,取前 个最小值,即为前 行的所有可能数组中的前 个最小值。
因此,我们可以定义一个数组 ,用于存储此前遍历到的行的前 个最小数组和,初始时 只有一个元素 。
然后,我们遍历 的每一行 ,将 中的每个元素与 中的每个元素相加,将得到的所有结果排序后,取前 个最小值作为新的 。继续遍历下一行,直到遍历完所有行。
最后返回 中的第 个数(下标 )即可。
时间复杂度 ,空间复杂度 。其中 和 分别是矩阵的行数和列数。
class Solution:
def kthSmallest(self, mat: List[List[int]], k: int) -> int:
pre = [0]
for cur in mat:
pre = sorted(a + b for a in pre for b in cur[:k])[:k]
return pre[-1]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate demonstrates understanding of binary search and heap-based approaches for solving matrix sum problems.
- question_mark
The candidate effectively applies binary search over the valid sum range and uses a priority queue for efficient sum management.
- question_mark
Look for a solution where the candidate avoids a brute-force approach and ensures that the algorithm works within the problem's constraints.
常见陷阱
外企场景- error
Failure to implement binary search correctly, leading to excessive computation.
- error
Not using the heap efficiently to track sums, causing performance issues for larger matrices.
- error
Confusing the problem with typical sum problems that don't involve sorted rows or the heap structure.
进阶变体
外企场景- arrow_right_alt
Consider solving with larger matrices, adjusting the binary search bounds appropriately.
- arrow_right_alt
Explore optimization strategies for reducing space complexity when working with very large k values.
- arrow_right_alt
Test variations where some rows are empty or have more than one element to ensure robustness.