Python求助,除最后一个点TLE其他WA

P2249 【深基13.例1】查找

MC_xjhjdA @ 2024-05-21 17:15:13

a,b=map(int,input().split())
l=list(map(int,input().split()))
i=list(map(int,input().split()))
def er(l,i):
    low=0 #最小数下标
    high=len(l)-1 #最大数下标
    while low<=high:
        mid=(low+high)//2
        if l[mid]==i:
            while l[mid-1]==i: #找到相同数的第一个
                mid-=1
            return mid+1
        elif l[mid]>i: #如果中间值比目标数大,在mid左半边找
            high=mid-1
        elif l[mid]<i: #如果中间值比目标数小,在mid右半边找
            low=mid+1
    return -1
for x in i:
    print(er(l,x))

by HAha20120522 @ 2024-05-21 17:17:22

找到之后不能立即返回,因为它是单调不减


by MC_xjhjdA @ 2024-05-31 19:26:00

a,b=map(int,input().split())
l=list(map(int,input().split()))
i=list(map(int,input().split()))
for x in i:
    low=0
    high=len(l)-1
    while low<=high:
        mid=(low+high)//2
        if l[mid]==x:
            while l[mid-1]==x:
                mid-=1
            print(mid+1,end=' ')
            break
        elif l[mid]>x:
            high=mid-1
        elif l[mid]<x:
            low=mid+1
    if l[mid]!=x:
        print(-1,end=' ')

@HAha201205221633 现在是最后一个点TLE,其他AC


|