头文件
#include <algorithm>
using namespace std;
lower_bound与upper_bound()查找一个元素的时间复杂度为O(log n);
一、数组中的lower_bound与upper_bound()
对于从小到大排序好的整型数组a[n],假设有a[5]={0,2,3,3,5},对于要查找的整型数val,有
1)int i=lower_bound(a,a+n,val)-a;
其中i返回值为数组中元素值大于等于val的第一个下标,相应地,如果数组中所有元素的值都小于val,则返回值为数组最后一个元素下标的下一个下标(另外一种说法是:i的返回值为val可以插入a数组的最前的位置)。
val=2,i=1;
val=3,i=2;
val=6,i=5;
2) int i=upper_bound(a,a+n,val)-a;
其中i返回值为数组中元素值大于val的第一个下标,相应地,如果数组中所有元素的值都小于等于val,则返回值为数组最后一个元素下标的下一个下标(另外一种说法是:i的返回值为val可以插入a数组的最后的位置)。
val=2,i=2;
val=3,i=4;
val=6,i=5;
二、 stl中的lower_bound与upper_bound()
用法和数组中的用法基本一样,不同之处在于写法和返回值,stl返回值为迭代器指向的指针,写法如下:
1、vector中的lower_bound与upper_bound()
vector<int> vec;
sort(vec.begin(),vec.end());//同样需要先排好序
vector<int>::iterator ita,itb;
ita=lower_bound(vec.begin(),v.end(),val);
ita=upper_bound(vec.begin(),v.end(),val);
2、set中的lower_bound与upper_bound()
set<int>s;
sort(s.begin(),s.end());//同样需要先排好序
set<int>::iterator sa,sb;
sa=s.lower_bound(val);
sb=s.upper_bound(val)
3、map中的lower_bound与upper_bound();
map<int,int>ma;
sort(ma.begin(),ma.end());
map<int,int>::iterator ita,itb;
ita=lower_bound(val);
itb=upper_bound(val);