74. 搜索二维矩阵
思路:把二维数组看做是一维数组,而且是有序的,使用二分查找。
时间复杂度O(log(mn))
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
def binarysearch(nums,left,right,target):
while left<=right:
mid = (left+right)//2
midnum = nums[mid//n][mid%n] # 注意
if midnum == target:
return True
elif midnum > target:
right = mid-1
else:
left = mid+1
return False
if not matrix: return False
m,n = len(matrix),len(matrix[0])
return binarysearch(matrix,0,m*n-1,target)
240. 搜索二维矩阵 II
思路:左下角是当列最大的元素,当行最小的元素。从左下角出发去寻找,最远找到右上角。
时间复杂度O(m+n)
class Solution:
def searchMatrix(self, matrix, target):
#
if not matrix: return False
m,n = len(matrix),len(matrix[0])
i,j = m-1,0
while i>=0 and j<n:
if matrix[i][j]==target:return True
elif matrix[i][j]>target:
i-=1
else:
j+=1
return False