- 数的范围
题目
提交记录
讨论
题解
视频讲解
给定一个按照升序排列的长度为n的整数数组,以及 q 个查询。
对于每个查询,返回一个元素k的起始位置和终止位置(位置从0开始计数)。
如果数组中不存在该元素,则返回“-1 -1”。
输入格式
第一行包含整数n和q,表示数组长度和询问个数。
第二行包含n个整数(均在1~10000范围内),表示完整数组。
接下来q行,每行包含一个整数k,表示一个询问元素。
输出格式
共q行,每行包含两个整数,表示所求元素的起始位置和终止位置。
如果数组中不存在该元素,则返回“-1 -1”。
数据范围
1≤n≤100000
1≤q≤10000
1≤k≤10000
输入样例:
6 3
1 2 2 3 3 4
3
4
5
输出样例:
3 4
5 5
-1 -1
#include <bits/stdc++.h>
using namespace std;
const int N=1e5+5;
int n,a[N],m,x,l,r,mid,ans1,ans2;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
for(int i=0;i<n;i++)
cin >> a[i];
while(m--)
{
cin >> x;
l=0,r=n-1,ans1=n;
while(l<=r)
{
mid=(l+r)>>1;
if(a[mid]>=x)
ans1=mid,r=mid-1;
else
l=mid+1;
}
if(ans1>=n)
{
cout << "-1 -1" << endl;
continue;
}
l=0,r=n-1,ans2=n;
while(l<=r)
{
mid=(l+r)>>1;
if(a[mid]>x)
ans2=mid,r=mid-1;
else
l=mid+1;
}
ans2--;
if(ans2<0||ans1>ans2)
{
cout << "-1 -1" << endl;
continue;
}
cout << ans1 << " " << ans2 << endl;
}
return 0;
}