1. lower_bound和upper_bound
定义:假定一个长度为n的单调不下降a0,…,an-1数组和一个数k,lower_bound以二分查找的形式,找出ai>=k的最小地址。
二分搜索的时间复杂度为O(logn).
#include"algorithm" //std::lower_bound
lower_bound(begin,end,num)二分查找第一个大于或等于num的数字,找到返回该数字的**地址**,不存在则返回end。
upper_bound(begin,end,num)二分查找第一个大于num的数字,找到返回该数字的**地址**,不存在则返回end。
lower_bound(begin,end,num,comp)其中comp函数限制了二分查找是**大于等于**换是**小于等于**
upper_bound(begin,end,num,comp)其中comp函数限制了二分查找是**大于**换是**小于**
lower_bound(begin,end,num)-begin 返回的便是对应数字的数组下标
举个栗子:
#include"iostream"
#include"stdlib.h"
#include"algorithm"
#include"functional" // std::greater()
using namespace std;
int main() {
int a[5] = { 3,1,5,9,7 };
//由小到大的排序
sort(a, a + 5, less<int>());
for (int i = 0; i <= 4; i++)
cout << a[i];
//求第一个小于等于7的数的下标
cout << endl << lower_bound(a, a + 5, 7, greater<int>()) - a << endl;
cout << upper_bound(a, a + 5, 7, greater<int>()) - a << endl;
//求第一个大于等于7的数的下标
cout << lower_bound(a, a + 5, 7, less<int>()) - a << endl;
cout << upper_bound(a, a + 5, 7, less<int>()) - a << endl;
cout << lower_bound(a, a + 5, 7) - a << endl;
cout << upper_bound(a, a + 5, 7) - a;
system("pause");
}
此程序的结果为
2. upper_bound() - lower_bound()
用来判断数组中是否存有某个数
举个栗子:
int a[5] = { 5,3,1,9,7 };
upper_bound(a, a + 5, 3) - lower_bound(a, a + 5, 3)
- 当数组中存在3,upper_bound()返回3之后一个数的位置,lower_bound()返回3的位置,相减得1
- 当数组中不存在3,则upper_bound()和lower_bound()均指向3之后一个数的位置,相减得0
#include"iostream"
#include"algorithm"
#include"stdlib.h"
using namespace std;
int main() {
int a[5] = { 5,3,1,9,7 };
sort(a, a + 5);
cout << upper_bound(a, a + 5, 3) - lower_bound(a, a + 5, 3) << endl;
cout << upper_bound(a, a + 5, 4) - lower_bound(a, a + 5, 4) << endl;
system("pause");
}
此程序结果: