c++实现lower_bound和upper_bound

#include <bits/stdc++.h>
using namespace std;
int a[] = {0,1,3,3,5,6,7,8,9,20,21,21,21,30,41,41,41,41,41,45,60};
// 查找第一个大于等于x的位置
int lower_bound(int l, int r, int x) {
    while (l <= r) {
        int mid = l+r>>1;
        if (a[mid] < x) l = mid+1;
        else r = mid-1;
    }
    return l;
}
// 查找第一个大于x的位置
int upper_bound(int l, int r, int x) {
    while (l <= r) {
        int mid = l+r>>1;
        if (a[mid] <= x) l = mid+1;
        else r = mid-1;
    }
    return l;
}
int main() {
    cout << lower_bound(1,20,41) << endl;
    cout << upper_bound(1,20,41) << endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/wstong/p/12897670.html