Find Peak Element

Find Peak Element

Binary Search Version - 36ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
def findPeakElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
left = 0
right = len(nums) - 1
while left < right - 1:
mid = (left + right) // 2
if nums[mid - 1] < nums[mid] and nums[mid] > nums[mid + 1]:
return mid
if nums[mid] < nums[mid + 1]:
left = mid + 1
else:
right = mid - 1
return left if nums[left] >= nums[right] else right

test code

1
2
3
4
5
6
7
8
9
10
11
12
13
In [7]: nums = [1,2,3,1]
In [17]: s = Solution(); t = s.findPeakElement(nums)
In [18]: t
Out[18]: 2
In [19]: nums = [1,2,1,3,5,6,4]
In [20]: s = Solution(); t = s.findPeakElement(nums)
In [21]: t
Out[21]: 5

leet code