二分边界问题
作者:
nxdxml
,
2021-03-07 10:03:59
,
所有人可见
,
阅读 420
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 105;
int n, k, l, r, a[N];
int main(){
cin >> n >> k;
for(int i = 1; i <= n; i ++ ) scanf("%d", &a[i]);
l = 1, r = n;
while(l < r){
int mid = l + r + 1 >> 1;
if(a[mid] < k) l = mid;
else r = mid - 1;
}
cout << r << " " << a[r] << endl;
l = 1, r = n;
while(l < r){
int mid = l + r >> 1;
if(a[mid] >= k) r = mid;
else l = mid + 1;
}
cout << r << " " << a[r] << endl;
return 0;
}
/*
输入
7 3
1 1 2 2 3 3 4
输出
4 2
5 3
结果分析
第一行是小于3的最大数
第二行是大于等于3的最小数
*/