边工作边刷题:70天一遍leetcode: day 24-1
Search a 2D Matrix
考点:方法很简单,对第0列和之后找到的行做两次2分,重点是用第一次二分后low和high的位置来确定行。对于二分没找到的情况:low这时候比high大1,low对应的是>target的元素,high对应的是<target的元素。对于这题,我们需要用high,因为行也是递增的。
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
m = len(matrix)
n = len(matrix[0])
low,high = 0,m-1
while low<=high:
mid = low + (high-low)/2
if matrix[mid][0]==target:
return True
elif matrix[mid][0]>target:
high=mid-1
else:
low=mid+1
print high
if high>=0 and high<m:
row = high
low,high = 0,n-1
while low<=high:
mid = low+(high-low)/2
print mid
if matrix[row][mid]==target:
return True
elif matrix[row][mid]>target:
high=mid-1
else:
low=mid+1
return False