forked from super30admin/Array-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path721. Accounts Merge.py
More file actions
38 lines (35 loc) · 1.17 KB
/
721. Accounts Merge.py
File metadata and controls
38 lines (35 loc) · 1.17 KB
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
"""
https://leetcode.com/problems/accounts-merge/
"""
class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
def dfs(index, temp_res):
nonlocal visited
if index in visited:
return
visited.add(index)
for email in accounts[index][1:]:
temp_res.add(email)
##child
children = hashmap[email]
for child in children:
dfs(child, temp_res)
result = []
hashmap = {}
visited = set()
if len(accounts) == 1:
return accounts
for i, account in enumerate(accounts):
emails = account[1:]
for email in emails:
if email in hashmap:
hashmap[email].append(i)
else:
hashmap[email] = [i]
for i, account in enumerate(accounts):
### for each index and temp_result we do dfs
temp_result = set()
dfs(i, temp_result)
if temp_result:
result.append([account[0]] + sorted(list(temp_result)))
return result