编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:
- 每行的元素从左到右升序排列。
- 每列的元素从上到下升序排列。

输入: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

输入: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
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
columns, rows = len(matrix), len(matrix[0])
# top, bottom, left, right 分别代表列的做小索引,列的最大索引, 行的做小索引, 行的最大索引
top, left, right, bottom = 0, 0, rows-1, columns-1
# 倒叙遍历矩阵的长度和宽度,以右上角为起始位置
if columns == 1:
return target in matrix[0]
if rows == 1:
return [target] in matrix
while right >= left and bottom >= top:
if matrix[top][right] > target: # 从右上角开始计算 如果右上角元素大于target 则在当前行左移一个单位
for i in range(right, left-1, -1):
if matrix[top][i] <= target: # 直到在当前行遇到比target小的值,开始向下移动
for j in range(top, bottom+1):
if matrix[j][i] == target: # 如果遇到相等的,返回True 否则返回 False
return True
elif matrix[top][right] < target: # 从右上角开始计算 如果右上角元素小于target 则在当前列下移一个单位
for j in range(top+1, bottom+1):
if matrix[j][right] >= target: # 直到在当前行遇到比target大的值,开始向左移动
for i in range(right, left-1, -1):
if matrix[j][i] == target: # 如果遇到相等的,返回True 否则返回 False
return True
else:
return True
return False # 一直没有找到相等的元素 返回False
2881



被折叠的 条评论
为什么被折叠?



