• 主页

# python返回两个有序数组的交集

kernelkoder 2020-04-23 12:46:06
python返回两个有序数组的交集
Write a program which takes as hput two sorted arrays, and returns a new array containing
elements that are present in both of the input arrays. The input arrays may have duplicate entries,
but the returned array should be free of duplicates. For example, the input is <2,3,3,5,5,6,7,7,8,12>
and (5,5,6,8 ,8,9,70,10), your output should be (5, 6, 8).
Hinf: Solve the problem if the input array lengths diffur by orders of magnitude. What if they are approximately
equal?
Solution: The brute-force algorithm is a "loop join" , i.e., traversing through all the elements of one
array and comparing them to the elements of the other array. Letm and n be the lengths of the two
input arrays

def intersect-two-sorted-arrays (A, B) :
return [a for i, a in enumerate(A)if (i== 0 or a != A[i - 1]) and a in B]
-----------

...全文
72 点赞 收藏 5

5 条回复
kernelkoder 2020年04月24日

cool_sql_9 2020年04月24日

weixin_45903952 2020年04月23日
i==0时，A[i-1]下标越界

chuifengde 2020年04月23日

cool_sql_9 2020年04月23日
i==0是对A数组中第一个数做的特殊处理，因为对第一个数，没法进行a != A[i - 1]的比较

1.5w+

3.3w+