📜  O(n)python中3个数组的交集(1)

📅  最后修改于: 2023-12-03 14:44:51.297000             🧑  作者: Mango

O(n)python中3个数组的交集

当需要找到多个数组的交集时,可以使用Python中的set数据结构。在Python中,set是一种无序且无重复元素的集合。

使用set的交集操作可以轻松地找到多个数组的交集。具体做法是将多个数组转换成set,然后使用交集操作符“&”(即and符号)即可。

下面是一个示例代码实现:

def get_common_elements(arr1, arr2, arr3):
    set1 = set(arr1)
    set2 = set(arr2)
    set3 = set(arr3)
    common_elements = set1 & set2 & set3
    
    return list(common_elements)

这里使用了Python内置函数set()将数组转换成set并对其取交集。“&”操作符用于求取集合的交集。

这段代码的时间复杂度为O(n),因为只需要对每个数组中的元素进行一次遍历。同时,由于set是基于哈希表实现的,查找元素的时间复杂度为O(1),因此该算法的效率非常高。

需要注意的是,由于这里将多个数组转换成了set,会导致元素的顺序被打乱。如果需要保持元素原来的顺序,可以使用一个列表保存交集的结果,然后再根据原来数组中的元素顺序来排序。

下面是一个加入元素排序的示例:

def get_common_elements(arr1, arr2, arr3):
    set1 = set(arr1)
    set2 = set(arr2)
    set3 = set(arr3)
    common_elements = set1 & set2 & set3
    result = []
    
    for elem in arr1:
        if elem in common_elements and elem not in result:
            result.append(elem)
            
    for elem in arr2:
        if elem in common_elements and elem not in result:
            result.append(elem)
            
    for elem in arr3:
        if elem in common_elements and elem not in result:
            result.append(elem)
            
    return result

这里将结果保存到了一个列表中,并且根据原始数组的顺序来排序。如果需要更好的性能,可以使用字典来替代列表,以达到更快的查找速度。

以上便是O(n)python中3个数组的交集的介绍。