-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSEARCH_IN_MATRIX.PY
More file actions
43 lines (36 loc) · 915 Bytes
/
SEARCH_IN_MATRIX.PY
File metadata and controls
43 lines (36 loc) · 915 Bytes
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
# SORTED ARRAY
# Input:
# n = 3, m = 3, x = 62
# matrix[][] = {{ 3, 30, 38},
# {36, 43, 60},
# {40, 51, 69}}
# Output: 0
# Explanation:
# 62 is not present in the matrix,
# so output is 0.
# METHOD 1 -- O(N*M) TIME AND O(1) SPACE COMPLEXITY
def Method_1(matrix,x):
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j]==x:
return 1
return 0
# METHOD 2 -- 0(N) TIME AND O(1) SPACE COMPLEXITY
def Method_2(matrix,x):
n=len(matrix)
m=len(matrix[0])
i=0
j=m-1
while i<n and j>=0:
if matrix[i][j]==x:
return 1
elif matrix[i][j]>x:
j-=1
else:
i+=1
return 0
if __name__ == '__main__':
matrix=[[3, 30, 38],
[36, 43, 60],
[40, 51, 69]]
print(Method_2(matrix,62))