-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfind-a-peak-2D.py
86 lines (70 loc) · 1.91 KB
/
find-a-peak-2D.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
#Find a peak element in a 2D array
"""
Input : 10 20 15
21 30 14
7 16 32
Output : 30
30 is a peak element because all its
neighbors are smaller or equal to it.
32 can also be picked as a peak.
Input : 10 7
11 17
Output : 17
"""
#code
class Solution:
v=0
def findMax(self,nums):
n = len(nums)
mid = int(n/2)
if n==1:
return self.v
if n>=2:
if nums[n-1]>=nums[n-2]:
self.v += n-1
return self.v
if nums[0]>=nums[1]:
return self.v
if nums[mid] >= nums[mid-1] and nums[mid] >= nums[mid+1]:
self.v += mid
return self.v
if nums[mid-1]>=nums[mid]:
self.v+=0
return self.findMax(nums[0:mid])
if nums[mid+1]>= nums[mid]:
self.v += mid
return self.findMax(nums[mid::])
def findPeakElement(self, array,row,col):
print(array)
#find middle row
mid = int(row/2)
# find peak of that row
ind_j = self.findMax(array[mid])
print(ind_j)
element1 = array[mid][ind_j]
print(ind_j,element1)
column = [r[ind_j] for r in array]
# find peak of that column
self.v =0
ind_i = self.findMax(column)
element2 = array[ind_i][ind_j]
print(ind_i,ind_j,element2)
if element1 == element2:
print("result",element1)
elif element1>element2:
print("result",element1)
else:
self.v =0
column = [r[ind_j] for r in array]
self.findMax(column)
sol = Solution()
# a = ([[1,2,1000],
# [1,6,4],
# [7,16,0]])
a = ([[10,7],
[17,17]])
# a = ([10, 8, 10, 10 ],
# [14, 13, 12, 11 ],
# [15, 9, 11, 21 ],
# [16, 17, 19, 20 ] );
sol.findPeakElement(a,2,2)