题意
题解
山脉数组峰值左侧斜率为正,右侧斜率为负,二分求峰值。对峰值左右两侧区间分别二分答案即可。
/**
* // This is the MountainArray's API interface.
* // You should not implement it, or speculate about its implementation
* class MountainArray {
* public:
* int get(int index);
* int length();
* };
*/
class Solution {
public:
int findInMountainArray(int target, MountainArray &mountainArr) {
int n = mountainArr.length();
int lb = -1, ub = n - 1;
while(ub - lb > 1){
int mid = (lb + ub) >> 1;
if(mountainArr.get(mid) >= mountainArr.get(mid + 1)) ub = mid;
else lb = mid;
}
int mount = ub;
lb = -1, ub = mount;
while(ub - lb > 1){
int mid = (lb + ub) >> 1;
if(mountainArr.get(mid) >= target) ub = mid;
else lb = mid;
}
if(mountainArr.get(ub) == target) return ub;
lb = mount, ub = n - 1;
while(ub - lb > 1){
int mid = (lb + ub) >> 1;
if(mountainArr.get(mid) <= target) ub = mid;
else lb = mid;
}
return mountainArr.get(ub) == target ? ub : -1;
}
};