AcWing 789. 数的范围
原题链接
简单
作者:
爱齐易
,
2021-03-12 13:53:48
,
所有人可见
,
阅读 310
AcWing 789. 数的范围
找区间段的左/右端点
1、找左端点,则认为自己在分界点右侧,如果m[mid]>=a,则往左侧去,mid本身可能是答案,故保留r=mid,否则右侧
2、找右端点,认为自己在左侧,如果m[mid]<=a,则向右侧缩小区间,mid本身可能是答案保留l=mid,否则左侧
然后套模板,细究细节边界
#include<iostream>
#include<cstdio>
using namespace std;
const int N = 100010;
int n, q;
int m[N];
int main() {
cin >> n >> q;
for(int i = 0; i < n; i++) scanf("%d",&m[i]);
int a;
for(int i = 0; i < q; i++) {
scanf("%d", &a);
int l = 0, r = n-1, mid;
while(l < r) {
mid = l + r >> 1;
if(m[mid] >= a) r = mid;
else l = mid + 1;
}
if(m[r] == a) {
cout << r << " ";
r = n-1;
while(l < r) {
mid = l + r + 1>> 1;
if(m[mid] <= a) l = mid;
else r = mid - 1;
}
cout << r << endl;
} else {
cout << "-1 -1" << endl;
}
}
return 0;
}