#162

Find Peak Element

specialist · 950 · lc medium +32 · verified · 46.8% accepted · 14,493 likes · top 31%

play →

Description

An element is a peak if it is strictly greater than both its neighbors.

Given a 0-indexed integer array nums, find any peak element and return its index. Any valid peak index is acceptable.

Treat nums[-1] = nums[n] = -∞ so a boundary element only needs to exceed its single neighbor.

Your algorithm must run in O(log n) time.

Example 1:

Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.

Example 2:

Input: nums = [1,2,1,3,5,6,4]
Output: 5
Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.

Code

1
2
3