-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAccountsMerge.java
71 lines (68 loc) · 2.64 KB
/
AccountsMerge.java
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* LeetCode
* 721. Accounts Merge
* https://leetcode.com/problems/accounts-merge/
* #Medium
*/
public class AccountsMerge {
public static void main(String[] args) {
AccountsMerge sol = new AccountsMerge();
System.out.println(sol.accountsMerge(Arrays.asList(
))); // [["John","[email protected]","[email protected]","[email protected]"],["John","[email protected]"],["Mary","[email protected]"]]
}
public List<List<String>> accountsMerge(List<List<String>> accounts) {
if (accounts == null || accounts.isEmpty()) return Collections.emptyList();
Map<String, String> emailToName = new HashMap<>();
Map<String, List<String>> graph = new HashMap<>();
for (List<String> account : accounts) {
String name = null;
for (String email : account) {
if (name == null) {
name = email;
continue;
}
graph.computeIfAbsent(email, x -> new ArrayList<>()).add(account.get(1));
graph.computeIfAbsent(account.get(1), x -> new ArrayList<>()).add(email);
emailToName.put(email, name);
}
}
Set<String> seen = new HashSet<>();
List<List<String>> res = new ArrayList<>();
for (String email : graph.keySet()) {
if (!seen.contains(email)) {
seen.add(email);
Deque<String> stack = new ArrayDeque<>();
stack.add(email);
List<String> component = new ArrayList<>();
while (!stack.isEmpty()) {
String node = stack.pop();
component.add(node);
for (String nei : graph.get(node)) {
if (!seen.contains(nei)) {
seen.add(nei);
stack.push(nei);
}
}
}
Collections.sort(component);
component.add(0, emailToName.get(email));
res.add(component);
}
}
return res;
}
}