lower_bound函数
函数lower_bound()在begin和end中的左闭右开区间进行二分查找,返回大于或等于val的第一个元素位置(迭代器)。如果所有元素都小于val,则返回last的位置。
注意STL中设计区间都是左闭右开,即[begin,end)。
lower_bound函数个人实现
在左闭右开的区间内进行二分查找。
//lower_bound 实现
int left_bsearch(vector<int>& nums, const int& target) {
int left = 0, right = nums.size() ; //注意right的位置为nums.size() ;
while (left < right) { //搜索区间为[left,right)
int mid = left + (right - left) / 2;
if (nums[mid] < target) left = mid + 1;
else
{
right = mid;
}
}
return left;
}
upper_bound函数
函数upper_bound()在begin和end中的左闭右开区间进行二分查找,返回的是被查序列中第一个大于查找值的位置(迭代器)。
upper_bound函数个人实现
//upper_bound 实现
int right_bsearch(vector<int>& nums, int target) { //右边界
int left = 0, right = nums.size() ; //注意right的位置为nums.size() ;
while (left < right) { //搜索区间为[left,right)
int mid = left + (right - left) / 2;
if (nums[mid] <= target) left = mid + 1;
else
{
right = mid;
}
}
return left;
}