-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAccountMerge.py
50 lines (37 loc) · 1.5 KB
/
AccountMerge.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
from typing import List
class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
reverse_dict = dict()
result = dict()
uf = UnionFind(len(accounts))
for index, emails in enumerate(accounts):
for email in emails[1::]:
if email in reverse_dict:
uf.union(reverse_dict[email], index)
reverse_dict[email] = index
for index, emails in enumerate(accounts):
root_index = uf.find_root(index)
if root_index not in result:
result[root_index] = set()
result[root_index].update(set(emails[1::]))
return [[accounts[k][0]] + sorted(list(v)) for k, v in result.items()]
class UnionFind:
def __init__(self, length):
self.list = list(range(length))
def find_root(self, n):
while n != self.list[n]:
n = self.list[n]
return n
def union(self, i, j):
i_root = self.find_root(i)
j_root = self.find_root(j)
if j_root < i_root:
j_root, i_root = i_root, j_root
self.list[j_root] = i_root
if __name__ == "__main__":
accounts = [["David", "[email protected]", "[email protected]"],
["David", "[email protected]", "[email protected]"],
["David", "[email protected]", "[email protected]"],
["David", "[email protected]", "[email protected]"],
["David", "[email protected]", "[email protected]"]]
print(Solution().accountsMerge(accounts))