Given an integer array nums, find a peak element, and return its index.
A peak element is an element that is strictly greater than its neighbors.
You may imagine that nums[-1] = nums[n] = -∞.
If the array contains multiple peaks, return the index to any one of the peaks.
You must write an algorithm that runs 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 2.
Example 2:
Input: nums = [1,2,1,3,5,6,4]
Output: 1 or 5
Explanation: Your function may return index 1, whose peak element is 2; or index 5, whose peak element is 6.
This problem asks you to return the index of any peak element in an integer array in O(log n) time. The standard solution is binary search: compare the middle element with its right neighbor. If nums[mid] < nums[mid + 1], the peak must lie on the right side; otherwise, it lies on the left side, including mid. Because the boundaries are treated as negative infinity and adjacent values are guaranteed to be different, the search always converges to a valid peak. The key idea is to use the local slope to decide which half still contains a peak.