AcWing 789. 数的范围
原题链接
简单
#include <iostream>
using namespace std;
const int maxn = 100005;
int n, q, x, a[maxn];
int main() {
scanf("%d%d", &n, &q);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
while (q--) {
scanf("%d", &x);
int l = 0, r = n - 1;
while (l < r) {
int mid = l + r +1 >> 1;
if (a[mid] <= x) l = mid;
else r = mid-1;
}
if (a[l] != x) {
printf("-1 -1\n");
continue;
}
//选出左边端点,找到判断条件, =可以在右边,所以 >=x 因此我们选择更新r1, 因为是r1=mid所以 不需要r1+1>>1,
int l1 = 0, r1 = n-1;
while (l1< r1) {
int mid = l1 + r1 >> 1;
if (a[mid] >= x) r1 = mid;
else l1 = mid +1; //注意l1要向上取整 ,确保能取到x
}
printf("%d %d\n", l1, l);
}
return 0;
}