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.
解题思路:
题目的提示中要求用log(n)的时间复杂度,因此,只能采用分治的思路,类似归并排序,JAVA实现如下:
public int findPeakElement(int[] nums) {
if(nums.length==1||nums[0]>nums[1])
return 0;
if(nums[nums.length-1]>nums[nums.length-2])
return nums.length-1;
int left=1,right=nums.length-2,mid=(left+right)/2;
if(findPeakElement(nums,mid,right)==-1)
return findPeakElement(nums,left,mid);
return findPeakElement(nums,mid,right);
}
static public int findPeakElement(int[] nums,int left,int right) {
if(left==right){
if(nums[left]>nums[left-1]&&nums[left]>nums[left+1])
return left;
return -1;
}
else if(left==right-1){
if(nums[left]>nums[left-1]&&nums[left]>nums[left+1])
return left;
else if(nums[right]>nums[right-1]&&nums[right]>nums[right+1])
return right;
return -1;
}
int mid=(left+right)/2;
if(findPeakElement(nums,mid+1,right)==-1)
return findPeakElement(nums,left,mid);
return findPeakElement(nums,mid+1,right);
}