#6 TLE求助 !悬关!!!

P2249 【深基13.例1】查找

sybnb @ 2024-01-08 21:24:25

#include<bits/stdc++.h>
using namespace std;
const int N=1e6;
int n,m;
int a[N],q;
int main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;++i){
        scanf("%d",&a[i]);
    }
    while(m--){
        scanf("%d",&q);
        if(a[1]>q||a[n]<q) {
            printf("-1 ");
            continue;
        }
        int l=1,r=n;
        int ans=-1;
        int afe=0;
        while(l<r){
            int mid=l+(r-l)/2;
            if(afe==mid){
                break;
            }
            afe=mid;
            if(a[mid]>q){
                r=mid;
            }
            else if(a[mid]<q){
                l=mid;
            }
            else if(a[mid]==q){
                if(mid==1) {
                    ans=mid;
                    break;
                }
                if(a[mid]==q&&a[mid-1]!=q) {
                    ans=mid;
                    break;
                }
                r=mid;
            }
        }
        printf("%d ",ans);
    }
    return 0;
}

by L_zaa_L @ 2024-01-08 21:29:22

@sybnb 将 N 设为 1e6+5,数组开小了


by sybnb @ 2024-01-08 21:31:38

@zaa 谢谢大佬


by sybnb @ 2024-01-08 21:32:02

已关注


|