题目链接:https://leetcode.cn/problems/search-a-2d-matrix-ii/
难度:中等
描述:
编写一个高效的算法来搜索 _m_ x _n_
矩阵 matrix
中的一个目标值 target
。该矩阵具有以下特性:
- 每行的元素从左到右升序排列。
- 每列的元素从上到下升序排列。
题解
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m, n = len(matrix), len(matrix[0])
row, col = m-1, 0
while row >= 0 and col < n:
if matrix[row][col] < target:
col += 1
elif matrix[row][col] > target:
row -= 1
else:
return True
return False