#方法一
#利用有序的特点,使用二叉搜索树的思想
class Solution:
def searchMatrix(self,matrix:List[List[int]],target:int)->bool:
if not matrix or not matrix[0]:
return False
rows=len(matrix) #行
cols=len(matrix[0]) #列
r,c=0,cols-1 #起点,右上角
while 0<=r<rows and 0<=c<cols:
if matrix[r][c]==target:
return True
elif matrix[r][c]<target:
r+=1
else:
c-=1
return False
#方法二
class Solution:
def searchMatrix(self,matrix:List[List[int]],target:int)->bool:
if not matrix or not matrix[0]:
return False
rows=len(matrix)
cols=len(matrix[0])
for i in range(rows):
if target>matrix[i][cols-1]: #如果不在这一行,就在下一行
continue
if target in matrix[i]: #检查是否在该行
return True
return False
思路:
这个二维矩阵,从左到右有序,从上到下有序,所以需要利用这个特点:
方法一:利用二叉搜索树的思想,从右上角出发开始寻找target,要么往左走,要么往右走,走的过程中,需要判断是否越界。
方法二:利用二分查找的思想,先找出目标值在哪一行,定位到行之后,再从该行里面去找。