二分查找
二分查找
https://www.nowcoder.com/practice/7bc4a1c7c371425d9faa9d1b511fe193?tpId=196&rp=1&ru=%2Factivity%2Foj&qru=%2Fta%2Fjob-code-total%2Fquestion-ranking
//判断条件是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; }