-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy path721-accounts-merge.java
79 lines (72 loc) · 2.41 KB
/
721-accounts-merge.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
72
73
74
75
76
77
78
79
class UnionFind {
int[] parents;
int[] rank;
public UnionFind(Integer n) {
parents = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++) {
parents[i] = i;
rank[i] = 0;
}
}
public Integer find(Integer p) {
while (p != parents[p]) {
parents[p] = parents[parents[p]];
p = parents[p];
}
return p;
}
public void union(Integer p, Integer q) {
Integer rootP = find(p);
Integer rootQ = find(q);
if (rootP == rootQ) {
return;
}
if (rank[rootP] > rank[rootQ]) {
parents[rootQ] = rootP;
} else if (rank[rootP] < rank[rootQ]) {
parents[rootP] = rootQ;
} else {
parents[rootP] = rootQ;
rank[rootQ] += 1;
}
}
}
class Solution {
public List<List<String>> accountsMerge(List<List<String>> accounts) {
UnionFind uf = new UnionFind(accounts.size());
HashMap<String, Integer> emailToId = new HashMap<>();
for (int i = 0; i < accounts.size(); i++) {
for (int j = 1; j < accounts.get(i).size(); j++) {
String mail = accounts.get(i).get(j);
if (emailToId.containsKey(mail)) {
uf.union(emailToId.get(mail), i);
} else {
emailToId.put(mail, i);
}
}
}
HashMap<Integer, Set<String>> idToEmails = new HashMap<>();
for (int i = 0; i < accounts.size(); i++) {
for (int j = 1; j < accounts.get(i).size(); j++) {
String mail = accounts.get(i).get(j);
Integer id = uf.find(i);
idToEmails.computeIfAbsent(id, k -> new HashSet<>()).add(mail);
}
}
List<List<String>> res = new ArrayList<>();
for (Map.Entry<Integer, Set<String>> entry: idToEmails.entrySet()) {
Integer id = entry.getKey();
Set<String> mails = entry.getValue();
ArrayList<String> info = new ArrayList<>();
info.addAll(mails);
Collections.sort(info);
info.add(0, accounts.get(id).get(0));
res.add(info);
}
return res;
}
}
// time O(mlogm + n + m), due to sort
// space O(m+n), due to hashmap, m is the number of mails, n is the number of accounts
// using graph and union find and sort