题目描述
编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
每行中的整数从左到右按升序排列。
每行的第一个整数大于前一行的最后一个整数。
题解 python3
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
# 从右上角开始查找,大于则行+1,小于则列-1
m = len(matrix)
n = len(matrix[0])
i, j = 0, n-1
while True:
if i < m and j >= 0:
if matrix[i][j] == target:
return True
elif matrix[i][j] < target:
i += 1
else:
j -= 1
else:
return False
附:大佬的6种题解方法https://leetcode-cn.com/problems/search-a-2d-matrix/solution/fu-xue-ming-zhu-liu-chong-fang-fa-bang-n-e20z/