问题描述
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 that
A[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 that
A[0] < A[1] < … A[i-1] < A[i] > A[i+1] > … > A[A.length - 1].
寻找数组中的波峰,并返回其索引。
举个例子:
Input: [0,2,1,0]
Output: 1
类似题:
[162] Find Peak Element{:target=”_blank”}
解法1
和162题
一样。
直接来看下实现:
class Solution {
public int peakIndexInMountainArray(int[] A) {
int n = A.length;
int l = 0, r = n - 1;
while (l < r){
int mid = l + r + 1 >> 1;
if (A[mid] > A[mid - 1]) l = mid;
else r = mid - 1;
}
return l;
}
}
Enjoy it !