Leetcode刷题记录32——搜索二维矩阵 II
题源:https://leetcode.cn/problems/search-a-2d-matrix-ii/description/?envType=study-plan-v2&envId=top-100-liked
题目描述:
思路一:
💡 解题思路:利用矩阵有序特性 + 双指针法(Z 字形搜索)
由于矩阵每一行和每一列都是有序的,我们可以利用这个特性,避免暴力遍历所有元素。
✅ 核心思想:
我们从矩阵的 右上角 开始搜索:
- 如果当前值等于 target:找到目标,返回 True
- 如果当前值大于 target:说明这一列的下面都更大,可以直接排除 → 向左移动(
col -= 1
) - 如果当前值小于 target:说明这一行的左边都更小,可以直接向下找更大的 → 向下移动(
row += 1
)
这样我们就能像“走楼梯”一样,逐步逼近目标值。
代码如下:
class Solution(object):def searchMatrix(self, matrix, target):""":type matrix: List[List[int]]:type target: int:rtype: bool"""row = 0col = len(matrix[0]) - 1while row <= len(matrix) -1 and col >= 0:if target == matrix[row][col]:return Trueelif target > matrix[row][col]:row += 1else:col -= 1return False
执行时间如下: