File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments