Find Peak Element
Description
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:
Example 2:
Note:
Your solution should be in logarithmic complexity.
Solution
Proof:
Loop invariant:
nums[l-1] < nums[l]
andnums[r] > nums[r+1]
and the peak's index is in[l, r]
.mid + 1
r
.If
nums[mid] < nums[mid + 1]
,If
nums[mid+1], ..., nums[r]
is monotonically increasing,nums[r]
is the peak element.Otherwise, there must be an index
i
in[mid+1, r-1]
such thatnums[i] > max(nums[i-1], nums[i+1])
.nums[i]
is the peak element.So the peak index is in
[mid+1, r]
.
Otherwise, the peak index is in
[l, mid]
. The proof is similar.
Last updated