峰值元素是指其值大于左右相鄰值的元素堕油。
給定一個(gè)輸入數(shù)組 nums潘飘,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引馍迄。
數(shù)組可能包含多個(gè)峰值福也,在這種情況下局骤,返回任何一個(gè)峰值所在位置即可攀圈。
你可以假設(shè) nums[-1] = nums[n] = -∞。
示例 1:
輸入: nums = [1,2,3,1]
輸出: 2
解釋: 3 是峰值元素峦甩,你的函數(shù)應(yīng)該返回其索引 2赘来。
示例 2:
輸入: nums = [1,2,1,3,5,6,4]
輸出: 1 或 5
解釋: 你的函數(shù)可以返回索引 1,其峰值元素為 2凯傲;
或者返回索引 5犬辰, 其峰值元素為 6。
解
題目中已經(jīng)說(shuō)明了nums[-1] = nums[n] = -∞冰单,所以使用二分查找幌缝,如果nums[i]>nums[i+1],說(shuō)明在i之前必有峰值,否則在i之后有峰值
public static int findPeakElement(int[] nums) {
int start = 0,end = nums.length-1;
int mid = 0;
while(start<end) {
mid = (start + end) / 2;
if(nums[mid]>nums[mid+1])
end = mid;
else if(nums[mid]<nums[mid+1])
start = mid+1;
}
return start;
}