在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集背后的数据结构是什么?
答案 0 :(得分:20)
intersection algorithm始终以O(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
[回答附加编辑中的问题]集合后面的数据结构是hash table。
答案 1 :(得分:12)
答案似乎是a search engine query away。您也可以使用此direct link to the Time Complexity page at python.org。快速摘要:
Average: O(min(len(s), len(t))
Worst case: O(len(s) * len(t))
编辑:正如雷蒙德在下面指出的那样,“最坏情况”情景不太可能发生。我最初把它包括在内是彻底的,我将其留下来为下面的讨论提供背景,但我认为雷蒙德是对的。
答案 2 :(得分:1)
可以使用m,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
步骤3中的循环将运行n/m
次迭代,每次迭代将采用O(m*logm)
,因此m&lt;&lt;&lt;&lt;&lt; Ñ
我认为这是存在的最佳下限