二分查找炸了,救命!!!
查看原帖
二分查找炸了,救命!!!
1046223
a_blue_fool楼主2023/12/4 18:51
#include <iostream>
#include <cstdio>

using namespace std;

int search(int ans , int list[] , int l , int r)
{
    int key;

    while (l <= r)
    {
        key = l+(l+r)/2;

        if (list[key] > ans)
        {
            r = key-1;
        }
        else if (list[key] < ans)
        {
            l = key+1;
        }
        else
        {
            return key;
        }
    }

    return -1;
}

int main()
{
    int n , t , tmp;
    scanf("%d%d" , &n , &t);

    int list[n];

    for (int i = 0 ; i < n ; i++)
    {
        scanf("%d" , &list[i]);
    }

    for (int i = 0 ; i < t ; i++)
    {
        scanf("%d" , &tmp);
        printf("%d\n" , search(tmp , list , 0 , n-1)-1);
    }

    return 0;
}
2023/12/4 18:51
加载中...