-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind_peak_element.py
25 lines (20 loc) · 960 Bytes
/
find_peak_element.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
"""
A peak element is an element that is strictly greater than its neighbors.
Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.
You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.
You must write an algorithm that runs in O(log n) time.
"""
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
left = 0
right = len(nums) - 1
while left <= right:
mid = (left + right) // 2
# left neighbour greater
if mid > 0 and nums[mid] < nums[mid - 1]:
right = mid - 1
# right neighbour greater
elif mid < len(nums) - 1 and nums[mid] < nums[mid + 1]:
left = mid + 1
else:
return mid