Skip to content

Commit 341796b

Browse files
Chris WuChris Wu
Chris Wu
authored and
Chris Wu
committed
peak-index-in-a-mountain-array.py
1 parent e7a2571 commit 341796b

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
"""
2+
Take a look at the code first.
3+
If `A[p]<A[p+1]`, it means the `p` and `p+1` is at the left side of the mountain,
4+
We move `l` to `p+1`, since the peak must be at `p+1` or the right of the `p+1`.
5+
Else, it means the `p` and `p+1` is at the right side of the mountain,
6+
We move the `r` to `p`, since the peak must be at `p` or the left of the `p`.
7+
The `l` and `r` will move closer and closer to the peak until they meet together.
8+
The time complexity is `O(LogN)`
9+
"""
10+
class Solution(object):
11+
def peakIndexInMountainArray(self, A):
12+
l = 0
13+
r = len(A)-1
14+
while l<r:
15+
p = (l+r)/2
16+
if A[p]<A[p+1]:
17+
l = p+1
18+
else:
19+
r = p
20+
return l

0 commit comments

Comments
 (0)