详细见详细见《算法竞赛入门》P229
- 这里用的是左闭右开空间[left , right)
- upper_bound返回的是target应该插入的位置或者最后一次出现位置的下一个位置
- 这里的实现就跟STL中的这两个函数功能类似
- STL源码学习—-lower_bound和upper_bound算法
#include<vector>
#include<iostream>
using namespace std;
//返回target在有序向量A中出现的第一个位置
//如果target不在A中,则是target应该插入的位置
int lower_bound(vector<int> &A, int target){
int len = A.size();
int l = 0, r = len;
while (l < r){
int mid = l + (r - l) / 2;
if (target == A[mid]){
r = mid;
}
else if (target>A[mid]){
l = mid + 1;
}
else{
r = mid;
}
}
return l;
}
//返回target在有序向量A中出现的第最后一个位置的下一个位置
//如果target不在A中,则是target应该插入的位置
int upper_bound(vector<int> &A,int target){
int len = A.size();
int l = 0, r = len;
while (l<r){
int mid = l + (r - l) / 2;
if (target == A[mid]){
l = mid+1;
}
else if (target>A[mid]){
l = mid + 1;
}
else{
r = mid;
}
}
return r;
}
int main(){
int data[] = { 1, 2, 6,6, 8, 9 };
vector<int> A(data, data + 6);
cout <<"lower bound:"<< lower_bound(A, 6) << endl;
cout <<"upper bound:"<< upper_bound(A, 6) << endl;
return 0;
}
结果:
2
4