题目描述:
思路一:
💡 解题思路:利用矩阵有序特性 + 双指针法(Z 字形搜索)
由于矩阵每一行和每一列都是有序的,我们可以利用这个特性,避免暴力遍历所有元素。
✅ 核心思想:
我们从矩阵的 右上角 开始搜索:
- 如果当前值等于 target:找到目标,返回 True
- 如果当前值大于 target:说明这一列的下面都更大,可以直接排除 → 向左移动(
col -= 1
) - 如果当前值小于 target:说明这一行的左边都更小,可以直接向下找更大的 → 向下移动(
row += 1
)
这样我们就能像"走楼梯"一样,逐步逼近目标值。
代码如下:
python
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
row = 0
col = len(matrix[0]) - 1
while row <= len(matrix) -1 and col >= 0:
if target == matrix[row][col]:
return True
elif target > matrix[row][col]:
row += 1
else:
col -= 1
return False
执行时间如下: