First common element from two lists

后端 未结 10 1107
执笔经年
执笔经年 2020-12-20 14:07
x = [8,2,3,4,5]
y = [6,3,7,2,1]

How to find out the first common element in two lists (in this case, \"2\") in a concise and elegant way? Any list

10条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-20 15:01

    Using a for loops with in will result in a O(N^2) complexity, but you can sort y here and use binary search to improve the time complexity to O(NlogN).

    def binary_search(lis,num):
        low=0
        high=len(lis)-1
        ret=-1  #return -1 if item is not found
        while low<=high:
            mid=(low+high)//2
            if numlis[mid]:
                low=mid+1
            else:
                ret=mid
                break
    
        return ret
    
    x = [8,2,3,4,5]
    y = [6,3,7,2,1]
    y.sort()
    
    for z in x:
        ind=binary_search(y,z)
        if ind!=-1
            print z
            break
    

    output: 2

    Using the bisect module to perform the same thing as above:

    import bisect
    
    x = [8,2,3,4,5]
    y = [6,3,7,2,1]
    y.sort()
    
    for z in x:
        ind=bisect.bisect(y,z)-1  #or use `ind=min(bisect.bisect_left(y, z), len(y) - 1)`
        if ind!=-1 and y[ind] ==z:
            print z      #prints 2
            break     
    

提交回复
热议问题