-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSearch-A-2D-Matrix.py
87 lines (83 loc) · 2.32 KB
/
Search-A-2D-Matrix.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
## Python Solution 1:
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m=len(matrix)
if m==0:
return False
n=len(matrix[0])
for i in range(m):
for j in range(n):
if matrix[i][j]==target:
return True
return False
## Python Solution 2:
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m=len(matrix)
if m==0:
return False
n=len(matrix[0])
for i in range(m):
start = 0
end = n-1
while end>=start:
mid = start + (end-start)//2
if matrix[i][mid] == target:
return True
if matrix[i][mid]<target:
start=mid+1
if matrix[i][mid]>target:
end=mid-1
return False
## Python Solution 3:
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m=len(matrix)
if m==0:
return False
n=len(matrix[0])
i=0
j=n-1
while i<m and j>=0:
if matrix[i][j]==target:
return True
elif matrix[i][j]>target:
j-=1
else:
i+=1
return False
## Python Solution 4:
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m=len(matrix)
if m==0:
return False
n=len(matrix[0])
start = 0
end = m*n-1
while end>=start:
mid = start + (end-start)//2
if matrix[mid//n][mid%n] == target:
return True
if matrix[mid//n][mid%n]<target:
start=mid+1
if matrix[mid//n][mid%n]>target:
end=mid-1
return False
## Python Solution 5:
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m=len(matrix)
if m==0:
return False
n=len(matrix[0])
i=m-1
j=0
while i>=0 and j<n:
if matrix[i][j]==target:
return True
elif matrix[i][j]>target:
i-=1
else:
j+=1
return False