method 1: brute force
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == target:
return True
return False
method 2: binary: nlog(n)
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
def binary(arr, target):
lo, hi = 0, len(arr) - 1
while lo <= hi:
mid = (lo + hi) // 2
if arr[mid] == target:
return True
elif arr[mid] > target:
hi -= 1
else:
lo += 1
return False
m, n = len(matrix), len(matrix[0])
for i in range(m):
if matrix[i][0] <= target and matrix[i][n-1] >= target:
return binary(matrix[i], target)
return False