赞
踩
给定三个数组以非降序排序, 请打印这些数组中的所有公共元素。
例子:
- 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快速解决此问题路口的字典。方法很简单,
Python通过字典交集在三个排序的数组中查找公共元素代码实现:
- # 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]
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。
更多数据结构和算法相关内容请参考:lsbin - IT开发技术:https://www.lsbin.com/
参考Python数据结构和算法相关内容:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。