Skip to content

Commit 6f8ab95

Browse files
Update and rename search_a_2d_matrix.cpp to search_a_2d_matrix.py
1 parent d52ae5b commit 6f8ab95

File tree

2 files changed

+34
-19
lines changed

2 files changed

+34
-19
lines changed

search_a_2d_matrix.cpp

Lines changed: 0 additions & 19 deletions
This file was deleted.

search_a_2d_matrix.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution:
2+
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
3+
4+
'''
5+
1. find target row
6+
2. find target element from 1
7+
'''
8+
9+
rowLen, colLen = len(matrix), len(matrix[0])
10+
top, bottom = 0, rowLen - 1
11+
12+
while top <= bottom:
13+
centreRow = top + (bottom - top) // 2
14+
if target > matrix[centreRow][-1]: # target below centreRow
15+
top = centreRow + 1
16+
elif target < matrix[centreRow][0]: # target above centreRow
17+
bottom = centreRow - 1
18+
else: # target in centreRow
19+
break
20+
21+
if not (top <= bottom): # element not found in matrix
22+
return False
23+
24+
# centreRow = top + (bottom - top) // 2
25+
left, right = 0, colLen - 1
26+
while left <= right:
27+
middle = left + (right - left) // 2
28+
if target > matrix[centreRow][middle]: # target towards right
29+
left = middle + 1
30+
elif target < matrix[centreRow][middle]: # target towards left
31+
right = middle - 1
32+
else:
33+
return True
34+
return False

0 commit comments

Comments
 (0)