File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ ## Accounts Merge
2
+
3
+ #### Description
4
+
5
+ [ link] ( https://leetcode.com/problems/accounts-merge/description/ )
6
+
7
+ ---
8
+
9
+ #### Solution
10
+
11
+ - See Code
12
+
13
+ 此题最巧妙之处在于使用邮箱并查集方式查找对应的账号,通过这种方式把所有连通的账号遍历完成,在DFS的过程中记录答案emails
14
+
15
+ ---
16
+
17
+ #### Code
18
+
19
+ > 最坏情况:O(n^2)
20
+
21
+ ``` python
22
+ class Solution :
23
+ def accountsMerge (self , accounts : List[List[str ]]) -> List[List[str ]]:
24
+ from collections import defaultdict
25
+ visited_accounts = [False ] * len (accounts)
26
+ emails_accounts_map = defaultdict(list )
27
+ res = []
28
+ # Build up the graph.
29
+ for i, account in enumerate (accounts):
30
+ for j in range (1 , len (account)):
31
+ email = account[j]
32
+ emails_accounts_map[email].append(i)
33
+
34
+ # DFS code for traversing accounts.
35
+ def dfs (i , emails ):
36
+ if visited_accounts[i]:
37
+ return
38
+ visited_accounts[i] = True
39
+ for j in range (1 , len (accounts[i])):
40
+ email = accounts[i][j]
41
+ emails.add(email)
42
+ for neighbor in emails_accounts_map[email]:
43
+ dfs(neighbor, emails)
44
+
45
+ # Perform DFS for accounts and add to results.
46
+ for i, account in enumerate (accounts):
47
+ if visited_accounts[i]:
48
+ continue
49
+ name, emails = account[0 ], set ()
50
+ dfs(i, emails)
51
+ res.append([name] + sorted (emails))
52
+ return res
53
+ ```
You can’t perform that action at this time.
0 commit comments