You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
难点是如何在山峰数组找到最高, 利用二分去比较 arr[mid] and arr[mid+1],然后决定去哪部分【这里的就像f(n)函数,在我的二分模板里】,
不过不同的是l =0, r=len-1 [l,r] -> while(l<r) break, this make sure mid+1 will not overflow
/** * // This is MountainArray's API interface. * // You should not implement it, or speculate about its implementation * interface MountainArray { * public int get(int index) {} * public int length() {} * } */classSolution {
publicintfindInMountainArray(inttarget, MountainArraymountainArr) {
//find the top and it always exists//search in left increading array//search in right increasing arrayinttopIndex = findTop(mountainArr);
if(target > mountainArr.get(topIndex)) return -1;
if(target == mountainArr.get(topIndex)) returntopIndex;
//[)intleftIndex = findLeft(target, mountainArr, 0, topIndex);
if(leftIndex>=0 && leftIndex<topIndex) returnleftIndex;
intrightIndex = findRight(target, mountainArr, topIndex, mountainArr.length());
if(rightIndex>topIndex && rightIndex<mountainArr.length()) returnrightIndex;
return -1;
}
intfindRight(inttarget,MountainArraymountainArr, intl, intr){
while(l<r){
intmid = (r-l)/2+l;
if(mountainArr.get(mid)==target) returnmid;
elseif(mountainArr.get(mid)>target) {
l = mid+1;
}else{
r = mid;
}
}
return -1;
}
//[)intfindLeft(inttarget,MountainArraymountainArr, intl, intr){
while(l<r){
intmid = (r-l)/2+l;
if(mountainArr.get(mid)==target) returnmid;
elseif(mountainArr.get(mid)<target) {
l = mid+1;
}else{
r = mid;
}
}
return -1;
}
//assume we must find the top index//how we find top index with such moutain arrayintfindTop(MountainArraymountainArr){
intl = 0, r = mountainArr.length()-1;
//[]while(l<r){
intmid = (r-l)/2+l;
//check mid+1 in the lengthif(mountainArr.get(mid)<mountainArr.get(mid+1)){
l = mid+1;
}else{
r = mid;
}
}
returnl;
}
}