题目描述
请在一个有序递增数组中(不存在相同元素),采用二分查找,找出值x的位置,如果x在数组中不存在,请输出-1!
输入
第一行,一个整数n,代表数组元素个数(n <= 106)
第二行,n个数,代表数组的n个递增元素(1<=数组元素值<=108)
第三行,一个整数x,代表要查找的数(0<=x<=108)
输出
x在数组中的位置,或者-1。
样例输入
10
1 3 5 7 9 11 13 15 17 19
3
样例输出
2
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,z;
cin>>n;
int a[n+5];
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
cin>>z;
int t=lower_bound(a+1,a+1+n,z)-a;
if(a[t]==z)
cout<<t;
else
cout<<-1;
return 0;
}