方法:hash表+并查集
建立一个hash表,key为集合元素,value为元素出现的集合,(或者用链表实现也可,因为链表构造比较麻烦所以偷懒了。)同时建立一个子hash,作用是建立当前元素所在集合与元素第一次出现的集合之间的关系,key为元素当前的集合,value为元素第一次出现的集合。这样通过遍历,就建立起了一个并查集结构,将所有有交集的元素指向同一个集合中。
然后建立一个列表,列表下标为集合编号,下标对应元素为并查集的根集合。通过子hash,汇总各集合对应的根集合,并将其更新到列表中。然后根据列表记录汇总合并对应集合即可。
注意在子hash中,元素第一次出现的集合可能并非根集合,此时要通过继续查找子hash找到根集合。
更新一下代码:
代码如下(python)
lista
=[['aaa','bbb','ccc'],['bbb','ddd'],['eee','fff'],['ggg'],['ddd','hhh']]
lenth
= len(lista
)
position
= [-1 for _
in range(lenth
)]
dict1
= {}
hash = {}
res
=[]
for i
in range(lenth
):
for j
in lista
[i
]:
if j
not in dict1
:
if i
not in hash:
hash[i
] = i
dict1
[j
] = i
else:
dict1
[j
] = i
else:
temp
= dict1
[j
]
hash[i
] = temp
temphash
= {}
for i
in range(lenth
):
j
= i
while hash[j
]!=j
:
j
= hash[j
]
position
[i
] = j
if j
not in temphash
:
temphash
[j
] = 1
for i
in range(lenth
):
if position
[i
]==i
:
continue
else:
lista
[position
[i
]].extend
(lista
[i
])
lista
[position
[i
]] = list(set(lista
[position
[i
]]))
for key
in temphash
:
res
.append
(lista
[key
])
print(res
)
'''