-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
6ddfd11
commit 24821cc
Showing
1 changed file
with
69 additions
and
0 deletions.
There are no files selected for viewing
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,69 @@ | ||
# Solution-1 | ||
# Check which row target element is and then apply Binary Search in that particular row | ||
# Time complexity m*log(n) | ||
|
||
class Solution: | ||
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: | ||
m = len(matrix) # number of rows | ||
n = len(matrix[0]) # number of cols | ||
|
||
for row in range(m): | ||
# if element is in a row | ||
if target >= matrix[row][0] and target <= matrix[row][-1]: | ||
# Perform Binary Search | ||
left = 0 | ||
right = n - 1 | ||
|
||
while left <= right: | ||
mid = (left + right) // 2 | ||
|
||
if matrix[row][mid] == target: | ||
return True | ||
|
||
elif matrix[row][mid] < target: | ||
left = mid + 1 | ||
|
||
else: | ||
right = mid - 1 | ||
return False | ||
|
||
|
||
# Solution-2 | ||
# In above solution, we are checking all rows | ||
# we know all rows are also Sorted | ||
# So we can apply Binary Search in Rows as well, to find the exact row | ||
# Then apply Binary Search in that row (to find target) - same as above. | ||
|
||
class Solution: | ||
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: | ||
m = len(matrix) # number of rows | ||
n = len(matrix[0]) # number of cols | ||
|
||
top, bottom = 0, n - 1 | ||
|
||
# Apply Binary search on rows to find in whc=ich row | ||
# element resides | ||
while top <= bottom: | ||
row = (top + bottom) // 2 | ||
if target > matrix[row][-1]: | ||
top = row + 1 | ||
elif target < matrix[row][0]: | ||
bottom = row - 1 | ||
else: | ||
break | ||
|
||
# Once we find the row | ||
# apply Binary Search in that row. | ||
if top <= bottom: | ||
row = (top + bottom) // 2 | ||
left, right = 0, cols - 1 | ||
while left <= right: | ||
mid = (left + right) // 2 | ||
if matrix[row][mid] == target: | ||
return True | ||
elif matrix[row][mid] < target: | ||
left = mid + 1 | ||
else: | ||
right = mid - 1 | ||
|
||
return False |