题目:

有一个长度为n的序列,q次查找,每一次查找输入一个值x,需要你找出序列中不超过x的最大数字,如果存在这种数字,请输出这个数字,否则请输出-1.

输入:
13 3
2 5 8 10 15 25 35 45 50 60 70 80 90
24
45
1
输出:
15
45
-1
分析:这道题不难,就是判断的条件不好判断。
源码:

include

using namespace std;
int main(void)
{

int n,q;
cin>>n>>q;
int arr[n+1];
for(int i=1;i<=n;i++)
{
    cin>>arr[i];
}

for(int j=0;j<q;j++)
{
    int x,a=1,b=n;
    cin>>x;
    while(x>arr[1]&&x<arr[n]&&b-a>=0)
    {
        int md=arr[(a+b)/2];
        if(x==md)
        {
            cout<<md<<endl;
            a=-1;
            break;
        }else if(x>md)
        {
            a=(a+b)/2+1;
        }else if(x<md)
        {
            b=(a+b)/2-1;
        }
    }
    if(a==1)
    {
        cout<<-1<<endl;
    }else if(a!=-1)
    {
        cout<<arr[b]<<endl;
    }
}
return 0;

}