-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
solved: LC74. Search a 2D Matrix. -@iamserda
- Loading branch information
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
36 changes: 36 additions & 0 deletions
36
neetcodeio/algostructybeginners/Lv4-BinarySearch/search_2d_matrix_sol1.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |