Skip to content

Commit 552fbb8

Browse files
committed
solved: LC74. Search a 2D Matrix. -@iamserda
1 parent 091ba5e commit 552fbb8

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution:
2+
def binary_search(self, arr, target):
3+
if arr:
4+
L = 0
5+
R = len(arr) - 1
6+
while L <= R:
7+
mid = (L + R) // 2
8+
if target > arr[mid]:
9+
L = mid + 1
10+
elif target < arr[mid]:
11+
R = mid - 1
12+
else:
13+
return True
14+
return False
15+
16+
def search_matrix(self, matrix: list[list[int]], target: int) -> bool:
17+
if matrix:
18+
for arr in matrix:
19+
if target < arr[0] or target > arr[-1]:
20+
continue
21+
result = self.binary_search(arr, target)
22+
if result:
23+
return True
24+
return False
25+
26+
27+
# TESTING ARENA:
28+
sol = Solution()
29+
30+
matrix = [[1, 2, 4, 8], [10, 11, 12, 13], [14, 20, 30, 40]]
31+
target = 10
32+
assert sol.search_matrix(matrix, target) == True
33+
34+
matrix = [[1, 2, 4, 8], [10, 11, 12, 13], [14, 20, 30, 40]]
35+
target = 15
36+
assert sol.search_matrix(matrix, target) == False

0 commit comments

Comments
 (0)