Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9590fd9

Browse files
authored
Create Search_a_2D_Matrix_II.py
1 parent 64d3e3c commit 9590fd9

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Solution - 1: For every row, apply Binary Search - Time: O(rows * log(cols))
2+
class Solution:
3+
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
4+
rows, cols = len(matrix), len(matrix[0])
5+
r,c = 0,0
6+
while r < rows and c < cols:
7+
start, end = matrix[r][0], matrix[r][-1]
8+
if target in range(start, end+1):
9+
low, high = 0, cols-1
10+
while low <= high:
11+
mid = (low + high) // 2
12+
if target == matrix[r][mid]:
13+
return True
14+
elif target < matrix[r][mid]:
15+
high = mid-1
16+
else:
17+
low = mid+1
18+
r += 1
19+
return False
20+
21+
22+
# Solution - 2: Start from the Top-right element and move the row and col pointer appropriately - Time: O(rows + cols)
23+
class Solution:
24+
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
25+
rows, cols = len(matrix), len(matrix[0])
26+
r,c = 0, cols-1
27+
"""Idea: Start from top right element and keep applying Binary Search."""
28+
while r < rows and c >= 0:
29+
if target == matrix[r][c]:
30+
return True
31+
elif target < matrix[r][c]:
32+
c -= 1
33+
else:
34+
r += 1
35+
return False

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /