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.
/*logrithmic solution*/
public class Solution {
public int findPeakElement(int[] num) {
for(int i=0,j=num.length-1,mid=(i+j)/2;i<j;mid=(i+j)/2){
if(mid==i){return num[mid]>num[j]?mid:j;}
else{
i=num[mid]>num[mid+1]?i:mid;
j=num[mid]>num[mid+1]?mid:j;
}
}
return 0;
}
}
/*method 1,O(n)*/
public class Solution {
public int findPeakElement(int[] num) {
int len=num.length;
if(len<=1)return 0;
for(int i=0;i<len-1;i++){
if(num[i]>num[i+1])return i;
}
return len-1;
}
}
两种方法:
the first one is logarithmic solution. some tricks;
if there are more than two element, then mid can as small as equal to i, because the result of division is integer. So we only need to handle this case in the logarithmic solution.
And then we need to handle the case when there is only one element.