Problem
A peak element is an element that is greater than its neighbors.
Given an input array nums
, where nums[i] ≠ nums[i+1]
, find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that nums[-1] = nums[n] = -∞
.
Example 1:
1 |
|
Example 2:
1 |
|
Note:
Your solution should be in logarithmic complexity.
Explanation
-
Runtime is $\log(n)$, so we need to use binary search method to solve it, so we will create left and right pointers.
-
When we find the middle element, we need to compare it with
nums[mid+1]
. Ifnums[mid] < nums[mid+1]
, then the peek element is on the right side because ifnums[mid+1] > nums[mid+2]
, then the peek element isnums[mid+1]
, ifnums[mid+1] < nums[mid+2]
, then we keep find the peek on the right side, which isnums[mid+2:end]
. Whenleft
andright
pointer meet, we returnleft
orright
.
Solution
1 |
|