描述
你给出一个整数数组(size为n),其具有以下特点:
- 相邻位置的数字是不同的
- A[0] < A[1] 并且 A[n - 2] > A[n - 1]
假定P是峰值的位置则满足A[P] > A[P-1]
且A[P] > A[P+1]
,返回数组中任意一个峰值的位置。
- It's guaranteed the array has at least one peak.
- The array may contain multiple peeks, find any of them.
- The array has at least 3 numbers in it.
样例
给出数组[1, 2, 1, 3, 4, 5, 7, 6]
返回1
, 即数值 2 所在位置, 或者6
, 即数值 7 所在位置.
挑战
Time complexity O(logN)
思路:
看到这个时间复杂度,我们第一想到的应该是二分查找。
首先 start = 1, end = len-2;
然后计算 mid = start + (end-start)/2;
如果 A[mid] > A[mid+1] , 那么 峰值肯定在前面或者就是mid位置,
反之, 峰值在mid之后。
Java代码:
public int findPeak(int[] A) {
// write your code here
if(A==null || A.length<3){
return 0;
}
int pre = 1, last = A.length-2;
while (pre+1<last){
int mid = pre+(last-pre)/2;
if(A[mid]>A[mid+1]){
last = mid;
}else{
pre = mid;
}
}
if(A[pre]<A[last]){
return last;
}else{
return pre;
}
}