M–二分查找
Time Limit: 600 ms Memory Limit: 65536 KiB
Submit Statistic Discuss
Problem Description
给出含有n个数的升序序列,保证序列中的数两两不相等,这n个数编号从1 到n。
然后给出q次询问,每次询问给出一个数x,若x存在于此序列中,则输出其编号,否则输出-1。
Input
单组输入。首先输入一个整数n(1 <= n && n <= 3000000),接下的一行包含n个数。
再接下来的一行包含一个正整数q(1 <= q && q <= 10000),表示有q次询问。
再接下来的q行,每行包含一个正整数x。
Output
对于每次询问,输出一个整数代表答案。
Sample Input
5
1 3 5 7 9
3
1
5
8
Sample Output
1
3
-1
Hint
Source
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int a[10000000];
int f(int a[],int left,int right,int n)
{
int mid;
while(left<=right)//这个地方一定要注意要小于等于,不然就不会A,因为如果相同的话就是中间,如果没有等号,那么中间那个数就没有办法执行了,除了快排之外第K小的数也是这样的
{
mid=(left+right)/2;
if(a[mid]==n)
{
return mid+1;
}
else if(a[mid]<n)
{
left=mid+1;
}
else if(a[mid]>n)
{
right=mid-1;
}
}
return -1;
}
int main()
{
int t,n,q;
scanf("%d",&t);
int i;
for(i=0; i<t; i++)
{
scanf("%d",&a[i]);
}
scanf("%d",&n);
while(n--)
{
scanf("%d",&q);
printf("%d\n",f(a,0,t-1,q));
}
return 0;
}