本题目要求读入n个整数,然后对他们进行排序。接着输入num组数(a,b,c),其中a为需查询的数,b和c为查询的区间下标。要求运用二分查找查询a的下标并输出。如果查询失败,则输出-1.
输入格式:
输入n(n<=100000),然后依次输入n个整数。接着输入num(num<100000),并依次输入num组整数(a,b,c)。
输出格式:
对于每一组数(a,b,c),输出a在区间b和c的下标,失败则输出-1。
输入样例:
在这里给出一组输入。例如:
10
9 8 0 0 3 5 2 1 8 7
2
8 5 9
3 0 9
输出样例:
在这里给出相应的输出。例如:
7
4
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10;
int arr[N],n;
int find(int a,int b,int c){
while(b<=c){
int mid = (b+c)/2;
if(arr[mid]==a)return mid;
else if(arr[mid]<a)b = mid + 1;
else c=mid - 1;
}
if(arr[b] != a)return -1;
}
int main (){
scanf("%d",&n);
for(int i=0;i<n;i++)scanf("%d",&arr[i]);
sort(arr,arr+n);
int x;
scanf("%d",&x);
while(x--){
int a,b,c;
cin>>a>>b>>c;
cout<<find(a,b,c)<<endl;
}
}