LeetCode 题解工作台
搜索二维矩阵 II
编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性: 每行的元素从左到右升序排列。 每列的元素从上到下升序排列。 示例 1: 输入: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[1…
4
题型
8
代码语言
3
相关题
当前训练重点
中等 · 二分·搜索·答案·空间
答案摘要
由于每一行的所有元素升序排列,因此,对于每一行,我们可以使用二分查找找到第一个大于等于 的元素,然后判断该元素是否等于 。如果等于 ,说明找到了目标值,直接返回 。如果不等于 ,说明这一行的所有元素都小于 ,应该继续搜索下一行。 如果所有行都搜索完了,都没有找到目标值,说明目标值不存在,返回 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:
- 每行的元素从左到右升序排列。
- 每列的元素从上到下升序排列。
示例 1:
输入:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5 输出:true
示例 2:
输入:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20 输出:false
提示:
m == matrix.lengthn == matrix[i].length1 <= n, m <= 300-109 <= matrix[i][j] <= 109- 每行的所有元素从左到右升序排列
- 每列的所有元素从上到下升序排列
-109 <= target <= 109
解题思路
方法一:二分查找
由于每一行的所有元素升序排列,因此,对于每一行,我们可以使用二分查找找到第一个大于等于 的元素,然后判断该元素是否等于 。如果等于 ,说明找到了目标值,直接返回 。如果不等于 ,说明这一行的所有元素都小于 ,应该继续搜索下一行。
如果所有行都搜索完了,都没有找到目标值,说明目标值不存在,返回 。
时间复杂度 ,其中 和 分别为矩阵的行数和列数。空间复杂度 。
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
for row in matrix:
j = bisect_left(row, target)
if j < len(matrix[0]) and row[j] == target:
return True
return False
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate applies binary search efficiently and explains the trade-off between row-by-row or column-by-column binary search.
- question_mark
The candidate explains the divide and conquer approach in the context of the matrix.
- question_mark
The candidate demonstrates an understanding of time and space complexity with regard to the constraints.
常见陷阱
外企场景- error
Not applying binary search correctly over the valid answer space, leading to inefficient solutions.
- error
Failing to reduce the problem size at each step, leading to a slower solution.
- error
Incorrectly handling edge cases such as empty rows, columns, or the target not existing in the matrix.
进阶变体
外企场景- arrow_right_alt
Optimizing the solution for larger matrices by considering different search strategies.
- arrow_right_alt
Handling special cases where the matrix contains duplicate values or non-standard sorts.
- arrow_right_alt
Adjusting the approach to search for multiple targets in the same matrix.