Skip to content

Commit

Permalink
solved: LC74. Search a 2D Matrix. -@iamserda
Browse files Browse the repository at this point in the history
  • Loading branch information
iamserda committed Feb 26, 2025
1 parent 091ba5e commit 552fbb8
Showing 1 changed file with 36 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
class Solution:
def binary_search(self, arr, target):
if arr:
L = 0
R = len(arr) - 1
while L <= R:
mid = (L + R) // 2
if target > arr[mid]:
L = mid + 1
elif target < arr[mid]:
R = mid - 1
else:
return True
return False

def search_matrix(self, matrix: list[list[int]], target: int) -> bool:
if matrix:
for arr in matrix:
if target < arr[0] or target > arr[-1]:
continue
result = self.binary_search(arr, target)
if result:
return True
return False


# TESTING ARENA:
sol = Solution()

matrix = [[1, 2, 4, 8], [10, 11, 12, 13], [14, 20, 30, 40]]
target = 10
assert sol.search_matrix(matrix, target) == True

matrix = [[1, 2, 4, 8], [10, 11, 12, 13], [14, 20, 30, 40]]
target = 15
assert sol.search_matrix(matrix, target) == False

0 comments on commit 552fbb8

Please sign in to comment.