-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLC1095_FindMountainArray.py
52 lines (46 loc) · 1.44 KB
/
LC1095_FindMountainArray.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
# """
# This is MountainArray's API interface.
# You should not implement it, or speculate about its implementation
# """
#class MountainArray:
# def get(self, index: int) -> int:
# def length(self) -> int:
class Solution:
def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int:
# time complexity: O(3logn) = O(logn)
length = mountain_arr.length()
# find peak
l, r = 1, length - 2
while l <= r:
m = (l + r) // 2
left, mid, right = mountain_arr.get(m - 1), mountain_arr.get(m), mountain_arr.get(m + 1)
if left < mid < right:
l = m + 1
elif left > mid > right:
r = m - 1
else:
break
peak = m
# search left side - ascending order
l, r = 0, peak
while l <= r:
m = (l + r) // 2
val = mountain_arr.get(m)
if val < target:
l = m + 1
elif val > target:
r = m - 1
else:
return m
# search right side - descending order
l, r = peak, length - 1
while l <= r:
m = (l + r) // 2
val = mountain_arr.get(m)
if val > target:
l = m + 1
elif val < target:
r = m - 1
else:
return m
return -1