http://www.cplusplus.com/reference/algorithm/
/*
target < 最小值 :返回index=left
target > 最大值 :返回index=right
其他:返回>=target的最小index
*/
int lower_bound(const vector<int>& nums, int left, int right, int target) {
int cnt = right - left, step = 0, index = 0;
while (cnt > 0) {
step = cnt / 2;
index = left + step;
if (nums[index] < target) {
left = ++index;
cnt -= step + 1;
}
else
cnt = step;
}
return left;
}
/*
返回的index对应的值永远比target大,即使不存在(小于最小->left,大于最大->right)
*/
int upper_bound(const vector<int>& nums, int left, int right, int target) {
int cnt = right - left, step = 0, index = 0;
while (cnt > 0) {
step = cnt / 2;
index = left + step;
if (!(target < nums[index] )) {
left = ++index;
cnt -= step + 1;
}
else
cnt = step;
}
return left;
}
bool binary_search(const vector<int>& nums, int left, int right, int target) {
left = lower_bound(nums, left, right, target);
return (left!=right && !(target<nums[left]));
}