标签:family nbsp lower 一个 turn str 死循环 bsp else
二分的原理是利用区间内值有序的特点, 不断让可行区间减半, 最终可行区间长度减到1得到答案
要保证二分能得到正确答案并且不会死循环, 要保证两个条件:
1. 解一直在可行区间里
2. 每次判断后可行区间都会缩小(特别是左右端点相距为1的时候)
闭区间 [low, high]
普通二分:pass
lower_bound:
初始参数为 low=0, high=n-1
p搜索区间为[low, high], 返回值候选区间[low, high+1]
A[mid]<key时,搜索区间更新为[mid+1,high], 返回值候选区间[mid+1, high+1]
A[mid]>=key时,搜索区间更新为[low,mid-1], 返回值候选区间[low, mid]
while (low<=high) 需要包含等于号,这是因为如果while (low<high),终止时low=high,返回值候选区间[low, high+1]有两个值。
while (low<=high) 终止时low>high, 即low>=high+1。又由于low<=high+1,所以low=high+1。此时候选区间只有一个元素low,low就是解。
int bsearch(int *A, int low, int high, int key){ //[low,high] int mid; while (low<=high){ mid = (low+high)/2; if (A[mid]==key) return mid; else if (A[mid]<key) low = mid+1; else high = low-1; } } int lower_bound(int *A, int low, int high, int key){ //[low,high] int mid; while (low<=high){ mid = (low+high)/2; if (A[mid]<key) low = mid+1; else high = low-1; } return low; }
A[mid]<key
标签:family nbsp lower 一个 turn str 死循环 bsp else
原文地址:https://www.cnblogs.com/hankunyan/p/9028410.html