-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSearch-A-2D-Matrix-II.py
72 lines (70 loc) · 1.86 KB
/
Search-A-2D-Matrix-II.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
## Python Solution 1:
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: 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])
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