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.
这道题要求在整数数组中找到任意一个峰值元素的下标,并且必须做到 O(log n) 时间复杂度。核心思路是二分查找:比较中点与右侧元素的大小,如果 nums[mid] < nums[mid + 1],说明峰值一定在右半边;否则峰值在左半边或就是 mid。由于题目保证边界可以视为负无穷,且相邻元素不相等,因此整个搜索过程可以稳定收敛到一个峰值位置。这类题的关键是利用“上坡一定通向某个峰顶”的性质,而不是线性扫描。