问题描述
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.
找到数组中任意一个波峰值,并返回其索引。
举个例子:
解法1
从上图中,你会发现一个性质:
如果nums[i] > nums[i - 1]
,那么它的右边肯定存在波峰,或者nums[i]
就是波峰。
同理,左峰同理。
来看下实现:
class Solution {
public int findPeakElement(int[] nums) {
int n = nums.length;
int l = 0, r = n - 1;
while (l < r){
int mid = l + r + 1 >> 1;
if (nums[mid] > nums[mid - 1]) l = mid;
else r = mid - 1;
}
return r;
}
}
Enjoy it !