Search a 2D Matrix II
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]Last updated
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]Last updated
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
n,m = len(matrix),len(matrix[0])
def helper(upperLeft,lowerRight):
x1,y1 = upperLeft
x2,y2 = lowerRight
if x1 > x2 or y1 > y2 or x2 >= n or y2 >= m:
return False
if x1==x2 and y1==y2:
return matrix[x1][y1] == target
x = (x1+x2)>>1
y = (y1+y2)>>1
if matrix[x][y] < target:
return helper((x+1,y1),(x2,y)) or helper((x1,y+1),(x,y2)) or helper((x+1,y+1),lowerRight)
elif matrix[x][y] > target:
return helper(upperLeft,(x,y)) or helper((x+1,y1),(x2,y)) or helper((x1,y+1),(x,y2))
else:
return True
return helper((0,0),(n-1,m-1))
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
n,m = len(matrix),len(matrix[0])
i,j=0,m-1
while i < n and j >=0:
if matrix[i][j] > target:
j -= 1
elif matrix[i][j] < target:
i += 1
else:
return True
return False