LeetCode 题解工作台
有序矩阵中第 K 小的元素
给你一个 n x n 矩阵 matrix ,其中每行和每列元素均按升序排序,找到矩阵中第 k 小的元素。 请注意,它是 排序后 的第 k 小元素,而不是第 k 个 不同 的元素。 你必须找到一个内存复杂度优于 O(n 2 ) 的解决方案。 示例 1: 输入: matrix = [[1,5,9],[1…
5
题型
4
代码语言
3
相关题
当前训练重点
中等 · 二分·搜索·答案·空间
答案摘要
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
给你一个 n x n 矩阵 matrix ,其中每行和每列元素均按升序排序,找到矩阵中第 k 小的元素。
请注意,它是 排序后 的第 k 小元素,而不是第 k 个 不同 的元素。
你必须找到一个内存复杂度优于 O(n2) 的解决方案。
示例 1:
输入:matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8 输出:13 解释:矩阵中的元素为 [1,5,9,10,11,12,13,13,15],第 8 小元素是 13
示例 2:
输入:matrix = [[-5]], k = 1 输出:-5
提示:
n == matrix.lengthn == matrix[i].length1 <= n <= 300-109 <= matrix[i][j] <= 109- 题目数据 保证
matrix中的所有行和列都按 非递减顺序 排列 1 <= k <= n2
进阶:
- 你能否用一个恒定的内存(即
O(1)内存复杂度)来解决这个问题? - 你能在
O(n)的时间复杂度下解决这个问题吗?这个方法对于面试来说可能太超前了,但是你会发现阅读这篇文章( this paper )很有趣。
解题思路
方法一
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
def check(matrix, mid, k, n):
count = 0
i, j = n - 1, 0
while i >= 0 and j < n:
if matrix[i][j] <= mid:
count += i + 1
j += 1
else:
i -= 1
return count >= k
n = len(matrix)
left, right = matrix[0][0], matrix[n - 1][n - 1]
while left < right:
mid = (left + right) >> 1
if check(matrix, mid, k, n):
right = mid
else:
left = mid + 1
return left
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Asks how to improve from O(n^2) memory to O(n) using matrix properties.
- question_mark
Probes whether you can count elements without flattening the matrix.
- question_mark
Checks if binary search on values versus indices is understood and correctly implemented.
常见陷阱
外企场景- error
Flattening the matrix and sorting uses excessive memory and ignores constraints.
- error
Miscounting elements when duplicates exist, which can return the wrong kth element.
- error
Confusing kth smallest with kth distinct element, leading to incorrect output.
进阶变体
外企场景- arrow_right_alt
Find the kth largest element in a sorted matrix using similar binary search logic.
- arrow_right_alt
Handle rectangular matrices where rows and columns are sorted differently.
- arrow_right_alt
Adapt heap solution to track positions in multiple sorted arrays or merged lists.