描述
A peak element is an element that is greater than its neighbors.
Given an input array where num[i] ≠ num[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 num[-1] = num[n] = -∞.
For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.
分析
给定一个数组,该数组相邻元素互不相同,找出其中任意一个极大值的索引。
如果采取从左到右依次遍历的话,时间复杂度 O(n) ,因此可以采用二分查找的方法。只要 nums[mid]<(>)nums[mid+1] ,则右边(左边)部分一定存在极大值,时间复杂度 0(log(n)) 。
代码
class Solution {
public:
int findPeakElement(vector<int>& nums) {
if (nums.empty()) return -1;
int lo = 0, hi = nums.size() - 1;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] < nums[mid + 1]) lo = mid + 1;
else hi = mid;
}
return lo;
}
};