(1)以字典方式构建构建并查集,用于联通同一user的email
class UnionSet:
def __init__(self):
self.father = dict()
def find(self, name):
if name not in self.father:
self.father[name] = name
return name
if self.father[name] == name:
return name
self.father[name] = self.find(self.father[name])
return self.father[name]
def union(self, x, y): #将y并入x类
root_x = self.find(x) #x位置元素,根节点为root_x编号元素
root_y = self.find(y) #y位置元素,根节点为root_y编号元素
if root_x != root_y:
self.father[root_y] = root_x #把root_y编号元素的父节点,替换为root_x
return
(2)由于name不唯一,email唯一。构建 email2name的映射同时通过并查集联结email
(3)遍历所有email,得到并查集中email根节点对应的emails
(4)通过email2name,得到email根节点 对应的name,并弹出emails
class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
us = UnionSet()
email2name = dict()
for account in accounts:
name = account[0]
index = len(account)
for i in range(1, index):
email2name[account[i]] = name
if i != index - 1:
us.union(account[i], account[i + 1])
email2emails = collections.defaultdict(list) ##构建email根节点的最小堆
for i in email2name:
heapq.heappush(email2emails[us.find(i)], i)
result = []
for email, emails in email2emails.items():
tmp = []
name = email2name[email]
tmp.append(name)
for i in range(len(emails)):
tmp.append(heapq.heappop(emails))
result.append(tmp)
return result
文章评论