两个有序数组求交集

面试碰到这个题
输入:l1 = [1,3,4,5,2,4,1,7]
l2 = [2,5,2,6,7,9]
输出:[5,2,7]

def comNumber(l1,l2):
    i=0
    j=0
    res = []
    while i < len(l1) and j < len(l2):
        if l1[i] == l2[j]:
            res.append(l1[i])
            i+=1
            j+=1
        elif l1[i]<l2[j]:
            i+=1
        else:
            j+=1
    return res

if __name__ == '__main__':
    l1 = [1,3,4,5,2,4,1,7]
    l2 = [2,5,2,6,7,9]
    b=comNumber(l1,l2)
    print(b)

输出:

[5, 2, 7]

猜你喜欢

转载自blog.csdn.net/weixin_40924580/article/details/84351584