整数二分查找

查找左边界
...

查找右边界
...

数的范围

#include<iostream>
using namespace std;
int num[100010];
int main(){
    int n , q;
    cin >> n >> q;
    for(int i = 0 ; i < n ; i ++) cin >> num[i];
    while(q --){
        int k;
        cin >> k;
        int l = 0 , r = n - 1;
        while(l < r){
            int mid = (l + r) >> 1;
            if(num[mid] >= k) r = mid;
            else l = mid + 1;
        }        
        if(num[l] == k)
            cout << l << " ";
        else{
            cout << -1 << " " << -1 << endl;
            continue;
        }
        l = 0 , r = n - 1;
        while(l < r){
            int mid = (l + r + 1) >> 1;
            if(num[mid] <= k) l = mid;
            else r = mid - 1;
        }    
        cout << l << endl;
    }
    return 0;
}
posted @ 2024-10-11 22:47  _l_x_y  阅读(0)  评论(0编辑  收藏  举报