【题目】
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.
Your solution should be in logarithmic complexity.
【解析】
因为只需要找打一个local maximum, 所以只需要用二分法。
开始 l =0;
r = num.length -1
MId = r/2
比如[ 1 ,2 ,3 4, 3, 2,1]
l = 0, r = 6 mid = 3 num[mid] = 4
如果 中间 < 右 ,l = 右 mid +1
否则:r = mid
这里,mid = 4 > 右,所以r = mid
mid = (l +r)/2
【解答】有点自欺欺人的做法的感觉。。。就是假装是sort的那种。
public int findPeakElement(int[] num) {
int l = 0;
int r = num.length -1;
int mid = r/2;
while(l<r){
if(num[mid] < num[mid+1]){
l = mid +1;
}else{
r = mid;
}
mid = (l + r)/2;
}
return l;
}