Skip to content

Commit f9f5d7c

Browse files
committed
Find Peak Element
1 parent f433690 commit f9f5d7c

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

162 Find Peak Element.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
'''
2+
A peak element is an element that is greater than its neighbors.
3+
4+
Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.
5+
6+
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
7+
8+
You may imagine that num[-1] = num[n] = -∞.
9+
10+
For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.
11+
12+
Note:
13+
Your solution should be in logarithmic complexity.
14+
'''
15+
16+
class Solution(object):
17+
def findPeakElement(self, nums):
18+
"""
19+
:type nums: List[int]
20+
:rtype: int
21+
"""
22+
left, right = 0, len(nums) - 1
23+
while left < right:
24+
mid = (right + left) // 2
25+
if nums[mid] < nums[mid + 1]:
26+
left = mid + 1
27+
else:
28+
right = mid
29+
return left
30+
31+
32+
if __name__ == "__main__":
33+
assert Solution().findPeakElement([1, 2, 3, 1]) == 2

0 commit comments

Comments
 (0)