为什么会有超时和wa

P2249 【深基13.例1】查找

ocean_of_life @ 2023-11-13 17:19:33

为什么我写了两个二分查找都会超时

int binsearch2(int arr[], int low, int high, int key)//迭代版本
{
    int mid;
    while (low <= high)
    {
        mid = low + (high - low) / 2;
        if ((arr[mid] == key))
        {
            while (arr[mid - 1] == arr[mid])
            {
                mid--;
            }
            break;
        }
        if (arr[mid] > key)
            high = mid - 1;
        else
            low = mid + 1;
    }
    if (low > high)
        mid = -2;
    return mid;

}
int binsearch1(int arr[], int low, int high, int key)递归版本
{
    if (low > high)
        return -2;//找不到就返回-2
    int mid = low + (high - low) / 2;
    if (arr[mid] == key) 
    {
        while (arr[mid - 1] == arr[mid])
        {
            mid--;
        }
        return mid;
    }
    else if (arr[mid] > key)
        return binsearch1(arr, low, mid - 1, key);
    else
        return binsearch1(arr, mid + 1, high, key);
}
#include<iostream>
using namespace std;
int arrn[1000005];
int main()
{
    unsigned int n, m, q;

    cin >> n >> m;
    for (int i = 0; i < n; i++)
    {
        scanf("%d",&arrn[i]);
    }
    for (int i = 0; i < m; i++)
    {
        scanf("%d", &q);
        int ans = binsearch1(arrn, 0, n - 1, q);
        printf("%d ", ans + 1);
    }

    return 0;
}

![这个是迭代的结果]("C:\Users\liang\Pictures\Screenshots\屏幕截图 2023-11-13 171226.png")

![递归的结果]("C:\Users\liang\Pictures\Screenshots\屏幕截图 2023-11-13 171648.png")

两个代码都是用二分查找找到目标元素,之后用一个while找到目标下标


by ocean_of_life @ 2023-11-13 17:22:20

@ocean_of_life

图片没发出来,但都是第一个 wa,最后一个tle,并且别的都是对的


by CCA_zhujunwei @ 2023-11-15 18:47:50

用map超好做的,试试这个

#include<bits/stdc++.h>
using namespace std;
map<int, int>ma;
int m, n, x, curX, l = -2147483648;
int main(){
    cin >> n >> m;
    for(int i = 1;i <= n;i++){
        cin >> x;
        if(l != x){
            ma[x] = i;
            l = x;
        }
    }
    for(int i = 1;i <= m;i++){
        cin >> curX;
        if(ma.count(curX)){
            cout<<ma[curX]<<" ";
        }
        else{
            cout<<-1<<" ";
        } 
    }
    return 0;
}

744ms,正好过


by sususu_123 @ 2023-11-17 12:46:32

@ocean_of_life 我也是。。找到原因了吗


|