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.
Note:
Your solution should be in logarithmic complexity.
public class Solution {
// 1,2,1,2,3
public int findPeakElement(int[] nums) {
if(nums==null) return -1;
//方法1:顺序搜索
// if(nums.length<2) return 0;
// for(int i=0; i<nums.length; i++){
// if(i==0){
// if(nums[i]>nums[i+1]) return i;
// }else if(i==nums.length-1){
// if(nums[i]>nums[i-1]) return i;
// }else if (nums[i]>nums[i-1] && nums[i]>nums[i+1])
// return i;
// }
// return -1;
int h=0, t=nums.length-1;
return findPeakHelper(nums, h, t);
}
<pre name="code" class="java" style="color: rgb(51, 51, 51); font-size: 14px;">//<span style="font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;">方法2:二分法</span>
int findPeakHelper(int[] nums, int h, int t){ //guarantee h,t are not neighbor. if(h>=t-1) return nums[h]>nums[t]?h:t; int mid=(h+t)/2; if(nums[mid]<nums[mid+1]) return findPeakHelper(nums,mid+1,t); else if(nums[mid]<nums[mid-1]) return findPeakHelper(nums,h,mid-1); else return mid; }}