题目
Let’s call an array A a mountain if the following properties hold:
A.length >= 3
- There exists some
0 < i < A.length - 1
such thatA[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]
- Given an array that is definitely a mountain, return any
i
such thatA[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]
.
Example 1:
Input: [0,1,0]
Output: 1
Example 2:
Input: nums = [10, 9, 8, 7],
Output: 10
我的想法
二分法呗。如果中点比后一个数小,说明在上坡,需要向后寻找,把开始指针移到中点位置;如果中点比前一个数小,说明在下坡,需要向前寻找,把结束指针移到中点位置
class Solution {
public int peakIndexInMountainArray(int[] A) {
int start = 0, end = A.length - 1;
while(start + 1 < end) {
int mid = start + (end - start) / 2;
if(A[mid] < A[mid + 1]) {
start = mid;
} else if(A[mid] < A[mid - 1]) {
end = mid;
} else {
return mid;
}
}
return A[start] > A[end] ? start : end;
}
}