在Python中,您可以通过以下方式获取两个集合的交集:
>>> s1 = {1, 2, 3, 4, 5, 6, 7, 8, 9}
>>> s2 = {0, 3, 5, 6, 10}
>>> s1 & s2
set([3, 5, 6])
>>> s1.intersection(s2)
set([3, 5, 6])
有人知道这个交集 (&
) 算法的时间复杂度吗?
编辑: 此外,有人知道 Python 集合背后的数据结构是什么吗?
在Python中,您可以通过以下方式获取两个集合的交集:
>>> s1 = {1, 2, 3, 4, 5, 6, 7, 8, 9}
>>> s2 = {0, 3, 5, 6, 10}
>>> s1 & s2
set([3, 5, 6])
>>> s1.intersection(s2)
set([3, 5, 6])
有人知道这个交集 (&
) 算法的时间复杂度吗?
编辑: 此外,有人知道 Python 集合背后的数据结构是什么吗?
集合背后的数据结构是一个哈希表,其典型性能是平摊的O(1)
查找和插入。
交集算法恰好循环min(len(s1), len(s2))
次。它每次循环执行一次查找,如果有匹配,则执行插入操作。在纯Python中,代码如下:
def intersection(self, other):
if len(self) <= len(other):
little, big = self, other
else:
little, big = other, self
result = set()
for elem in little:
if elem in big:
result.add(elem)
return result
答案似乎只需进行搜索引擎查询。您也可以使用这个到python.org的时间复杂度页面的直接链接。快速摘要:
Average: O(min(len(s), len(t))
Worst case: O(len(s) * len(t))
编辑:正如下面Raymond所指出的,"最坏情况"不太可能发生。我最初包括它是为了全面,现在我认为Raymond是正确的,但为了提供下面讨论的背景,我将保留它。
C
和平均值(且没有排序要求)。据我所知,最大所需复杂度为 O(n log n) + O(n)
,其中包括排序。然而,Big-O是一个上限,并且还有实际考虑因素… - user166390m,n
的集合的交集可以通过以下方式以O(max{m,n} * log(min{m,n}))
的时间复杂度实现:
假设m << n
。1. Represent the two sets as list/array(something sortable)
2. Sort the **smaller** list/array (cost: m*logm)
3. Do until all elements in the bigger list has been checked:
3.1 Sort the next **m** items on the bigger list(cost: m*logm)
3.2 With a single pass compare the smaller list and the m items you just sorted and take the ones that appear in both of them(cost: m)
4. Return the new set
n/m
次迭代,每次迭代需要 O(m*logm)
的时间,因此对于 m << n,您将具有 O(nlogm)
的时间复杂度。
elem in big
的最坏情况是 O(n)(当然平均情况是 O(1))。这就是交集最坏情况为 O(len(s)*len(t)) 的基础。你有什么想法吗? - Kurt McKee