求问二分是否有问题,最后一个节点超时

P2249 【深基13.例1】查找

zhaowufangnai @ 2024-03-07 23:21:05

#include<bits/stdc++.h>
using namespace std;
const int v = 1000010;
int a[v];
int num(int y,int z)
{
    int left = 0;
    int right = y;

    while (left <= right)
    {
        int middle = (left+right) / 2;
        if (a[middle] < z)
            left = middle + 1;
        else if (a[middle] > z)
            right = middle - 1;
        else if (a[middle] == z)
        {
            return middle;
            break;
        }
    }
    if (left > right)
        return -1;

}

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);
    std::cout.tie(0);
    int num( int y,int z);
    int n = 0, m = 0;
    cin >> n >> m;
    for (int i = 0; i < n; i++)
        cin >> a[i];
    for (int i = 0; i < m; i++)
    {
        int temp;
        cin >> temp;
        int x = num(n-1,temp);
        if (x == -1)
            cout << x << " ";
        else if (x == 0)
            cout << 1 << " ";
        else
        {
            int i = 0;
            for ( i = x-1;i>=0; i--)
             {
                if (a[i] != a[x])
                {
                    x = i + 1;
                    break;
                }
             }
    _ _ _ 
        cout << x+1<<" ";
        }

    }
    return 0;
}

by qusia_MC @ 2024-03-15 19:29:33

额你这个有一些极端情况会超时:

如果n=10^6并且所有的a_1,a_2…都相等的话根据你的程序在二分第一次就会退出,然后再用n/2的计算量算出第一次出现的位置。这样就是时间复杂度=O(n^2/2)简写为O(n^2)会爆掉


by qusia_MC @ 2024-03-15 19:29:59

@zhaowufangnai


by zhaowufangnai @ 2024-03-16 15:11:30

@William2019 解决了,谢谢


by qusia_MC @ 2024-03-16 18:29:32

6


|