-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolutioin.java
48 lines (46 loc) · 1.55 KB
/
Solutioin.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
class Solution {
private int[] p;
public List<List<String>> accountsMerge(List<List<String>> accounts) {
int n = accounts.size();
p = new int[n];
for (int i = 0; i < n; ++i) {
p[i] = i;
}
Map<String, Integer> emailId = new HashMap<>();
for (int i = 0; i < n; ++i) {
List<String> account = accounts.get(i);
String name = account.get(0);
for (int j = 1; j < account.size(); ++j) {
String email = account.get(j);
if (emailId.containsKey(email)) {
p[find(i)] = find(emailId.get(email));
} else {
emailId.put(email, i);
}
}
}
Map<Integer, Set<String>> mp = new HashMap<>();
for (int i = 0; i < n; ++i) {
List<String> account = accounts.get(i);
for (int j = 1; j < account.size(); ++j) {
String email = account.get(j);
mp.computeIfAbsent(find(i), k -> new HashSet<>()).add(email);
}
}
List<List<String>> res = new ArrayList<>();
for (Map.Entry<Integer, Set<String>> entry : mp.entrySet()) {
List<String> t = new LinkedList<>();
t.addAll(entry.getValue());
Collections.sort(t);
t.add(0, accounts.get(entry.getKey()).get(0));
res.add(t);
}
return res;
}
private int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
}