假设:
[(1,2),(3,4),(5,6),(3,7),(5,7)]
输出:
[set(1,2), set(3,4,5,6,7)]
说明:
(1,2)
(1,2), (3,4)
(1,2), (3,4), (5,6)
(1,2), (3,4,7), (5,6)
(1,2), (3,4,7,5,6)
我写了一个糟糕的算法:
Case 1: both numbers in pair are new (never seen before):
Make a new set with these two numbers
Case 2: one of the number in pair is new, other is already a part of some set:
Merge the new number in other's set
Case 3: both the numbers belong to some set:
Union the second set into first. Destroy the second set.
这个算法是否有更多的pythonic(奇特)解决方案?
答案 0 :(得分:4)
您可以使用Unionfind algorithm。首先,我们使用字典从对中创建树:
leaders = collections.defaultdict(lambda: None)
现在我们使用两个函数 - union
和find
- 来填充该树:
def find(x):
l = leaders[x]
if l is not None:
l = find(l)
leaders[x] = l
return l
return x
def union(x, y):
lx, ly = find(x), find(y)
if lx != ly:
leaders[lx] = ly
迭代所有对并将它们放入树中。
for a, b in [(1,2),(3,4),(5,6),(3,7),(5,7)]:
union(a, b)
然后看起来像这样:{1: 2, 2: None, 3: 4, 4: 7, 5: 6, 6: 7, 7: None}
最后,我们按照各自的“领导者”对这些数字进行分组,即find
返回的内容:
groups = collections.defaultdict(set)
for x in leaders:
groups[find(x)].add(x)
现在,groups.values()
为[set([1, 2]), set([3, 4, 5, 6, 7])]
复杂性应该是 O(nlogn)的顺序。