Problem
Given an integer arraynums, find a peak element and return its index. An element is a peak if it is strictly greater than its neighbors.
You may assume that
nums[-1] = nums[n] = -∞. The array may contain multiple peaks, so returning the index of any peak is valid.
Example(s)
Example 1
Input
nums = [1,2,3,1]
Output
2
Example 2
Input
nums = [1,2,1,3,5,6,4]
Output
5
Solution
This problem uses Binary Search by comparing the middle elementnums[mid] with its right neighbor nums[mid + 1].
If
nums[mid] > nums[mid + 1], we are on a descending slope. Therefore, a peak must exist at mid or somewhere to its left.
If
nums[mid] < nums[mid + 1], we are on an ascending slope. Therefore, a peak must exist somewhere to the right.
A peak is guaranteed to exist because the elements outside the array are treated as
-∞.
When we move along an ascending slope, the values must eventually either decrease, creating a peak, or reach the last element, which is greater than
-∞ and is therefore a peak.
We continue reducing the search range until
left == right. At that point, the remaining index is guaranteed to be a peak.
class Solution {
public int findPeakElement(int[] nums) {
int left = 0;
int right = nums.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] > nums[mid + 1]) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
}
Complexity
The time complexity isO(log n) because the search range is reduced by approximately half at every step.
The algorithm uses only a few variables, so the extra space complexity is
O(1).
Comments
No comments yet. Ask a question or share what helped.