将矩阵看为有序数组,只要把数组下标与矩阵下表对应上即可。二分查找,复杂度OlognN
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
if(not matrix):return False # 注意空矩阵的边界特殊情况
rows,clos=len(matrix),len(matrix[0]) # python多变量赋值很有意思
high,low=rows*clos-1,0
mid=(high+low)//2
while(low<=high): # 注意low==high的情况 要用=还要继续比一次
tmp=matrix[mid//clos][mid%clos]
if(target==tmp): return True
elif(target<tmp): high=mid-1
else: low=mid+1
mid=(low+high)//2
return False