Skip to content

Commit e7a2571

Browse files
Chris WuChris Wu
Chris Wu
authored and
Chris Wu
committed
find-peak-element.py
1 parent 3376772 commit e7a2571

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

problems/find-peak-element.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""
2+
Take a look at the code first.
3+
If `nums[p]<nums[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 findPeakElement(self, nums):
12+
l = 0
13+
r = len(nums)-1
14+
while l<r:
15+
p = (l+r)/2
16+
if nums[p]<nums[p+1]:
17+
l = p+1
18+
else:
19+
r = p
20+
return l
21+
22+
23+
#O(N) Solution
24+
class Solution(object):
25+
def findPeakElement(self, nums):
26+
if nums is None or len(nums)==0: return None
27+
for i in xrange(len(nums)):
28+
l = nums[i-1] if (i-1)>=0 else float('-inf')
29+
r = nums[i+1] if (i+1)<len(nums) else float('-inf')
30+
if nums[i]>l and nums[i]>r: return i
31+
return None

0 commit comments

Comments
 (0)