-
Notifications
You must be signed in to change notification settings - Fork 0
/
matrix_search.py
59 lines (50 loc) · 1.71 KB
/
matrix_search.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class Solution:
def searchMatrix1(self, matrix: List[List[int]], target: int) -> bool:
####### O(mlog(n))
def perform_binary(row, target):
l,r = 0, len(row) - 1
while l <= r:
m = l + (r-l) // 2
if row[m] == target:
return True
elif target < row[m]:
r = m-1
elif target > row[m]:
l = m+1
return False
for row in matrix:
if target <= row[-1]:
res = perform_binary(row, target)
if res:
return True
else:
continue
return False
def searchMatrix2(self, matrix: List[List[int]], target: int) -> bool:
######## O(log(m*n))
def perform_binary_rows(matrix, target):
l,r = 0, len(matrix) - 1
while l <= r:
m = l + (r-l) // 2
if matrix[m][0] <= target and target <= matrix[m][-1]:
return m
elif target < matrix[m][0]:
r = m-1
else:
l = m+1
return -1
rr = perform_binary_rows(matrix, target)
if rr == -1:
return False
def perform_binary_column(row, target):
l,r = 0, len(row) - 1
while l <= r:
m = l + (r-l) // 2
if row[m] == target:
return True
elif target < row[m]:
r = m-1
elif target > row[m]:
l = m+1
return False
return perform_binary_column(matrix[rr], target)