-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path721.accounts-merge.py
45 lines (35 loc) · 1.21 KB
/
721.accounts-merge.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
#
# @lc app=leetcode id=721 lang=python3
#
# [721] Accounts Merge
#
# @lc code=start
# TAGS: Union-Find, DFS
# REVIEWME: Union-Find, DFS
import collections
class UF:
def __init__(self, N):
self.parents = list(range(N))
def union(self, child, parent):
self.parents[self.find(child)] = self.find(parent)
def find(self, x):
if x != self.parents[x]:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
class Solution:
# 196 ms, 82.09%. Time: O(AlogA). Space: O(A). A is total length of each accounts[i]
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
uf = UF(len(accounts))
# Creat unions between indexes
ownership = {}
for i, (_, *emails) in enumerate(accounts):
for email in emails:
if email in ownership:
uf.union(i, ownership[email])
ownership[email] = i
# Append emails to correct index
ans = collections.defaultdict(list)
for email, owner in ownership.items():
ans[uf.find(owner)].append(email)
return [[accounts[i][0]] + sorted(emails) for i, emails in ans.items()]
# @lc code=end