Skip to content

Commit 5d57745

Browse files
committedDec 29, 2022
add search 2d matrix
1 parent c1896d5 commit 5d57745

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed
 

‎src/search_2d_matrix.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
6+
rows, cols = len(matrix), len(matrix[0])
7+
8+
top, bot = 0, rows - 1
9+
while top <= bot:
10+
row = (top + bot) // 2
11+
if target > matrix[row][-1]:
12+
top = row + 1
13+
elif target < matrix[row][0]:
14+
bot = row - 1
15+
else:
16+
break
17+
if top > bot:
18+
return False
19+
row = (top + bot) // 2
20+
left, right = 0, cols - 1
21+
while left <= right:
22+
middle = (left + right) // 2
23+
if target > matrix[row][middle]:
24+
left = middle + 1
25+
elif target < matrix[row][middle]:
26+
right = middle - 1
27+
else:
28+
return True
29+
return False

‎tests/test_search_2d_matrix.py

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from search_2d_matrix import Solution
2+
3+
testcase = [
4+
{
5+
"testcase": [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]],
6+
"target": 3,
7+
"result": True,
8+
}
9+
]
10+
11+
12+
def test_search_2d_matrix():
13+
for tc in testcase:
14+
matrix = tc["testcase"]
15+
target = tc["target"]
16+
ans = Solution().searchMatrix(matrix, target)
17+
assert ans == tc["result"]

0 commit comments

Comments
 (0)
Please sign in to comment.