Python |通过字典交集在三个排序数组中查找公共元素

给定三个按非降序排序的数组,打印这些数组中的所有公共元素。

null

例如:

Input:  ar1 = [1, 5, 10, 20, 40, 80]
        ar2 = [6, 7, 20, 80, 100]
        ar3 = [3, 4, 15, 20, 30, 70, 80, 120]
Output: [80, 20]

Input:  ar1 = [1, 5, 5]
        ar2 = [3, 4, 5, 5, 10]
        ar3 = [5, 5, 10, 20]
Output: [5, 5]

我们有解决这个问题的现有方案,请参考 在三个排序的数组中查找公共元素 链接我们可以使用python快速解决这个问题 十字路口 字典。方法很简单,

  1. 首先,使用 计数器() 方法
  2. 现在对三个字典执行交集操作,这将导致我们的字典在三个数组列表中具有公共元素及其频率。

# Function to find common elements in three
# sorted arrays
from collections import Counter
def commonElement(ar1,ar2,ar3):
# first convert lists into dictionary
ar1 = Counter(ar1)
ar2 = Counter(ar2)
ar3 = Counter(ar3)
# perform intersection operation
resultDict = dict (ar1.items() & ar2.items() & ar3.items())
common = []
# iterate through resultant dictionary
# and collect common elements
for (key,val) in resultDict.items():
for i in range ( 0 ,val):
common.append(key)
print (common)
# Driver program
if __name__ = = "__main__" :
ar1 = [ 1 , 5 , 10 , 20 , 40 , 80 ]
ar2 = [ 6 , 7 , 20 , 80 , 100 ]
ar3 = [ 3 , 4 , 15 , 20 , 30 , 70 , 80 , 120 ]
commonElement(ar1,ar2,ar3)


输出:

[80, 20]
© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享