//判断条件是left+1<right 这样在left和right相隔1的时候循环就停止了,避免某些特殊情况造成死循环的问题。最后根据left和right展开讨论即可。
public int upper_bound_ (int n, int v, int[] a) {
// write code here
if(a.length==0) return 1;
if(v>a[n-1]) return n+1;
int left = 0;
int right = n-1;
while(left+1<right){
int mid = (right-left)/2+left;
if(a[mid]>=v){//中值大于等于目标值 中值也有可能是答案 因此right=mid
right=mid;
}else left = mid+1;
}
if(a[left]>=v) return left+1;
else if(v<=a[right]) return right+1;
else return n+1;
}
京公网安备 11010502036488号