全TLE,望大佬指点

P2249 【深基13.例1】查找

BBY123 @ 2023-09-26 17:52:06


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

by zhangbo1000 @ 2023-09-28 10:39:22

你这个会在l==r且b[i]<a[mid]时死循环,把r=mid改成r=mid-1就好了


|