forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0721-accounts-merge.java
75 lines (63 loc) · 2 KB
/
0721-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
class Solution {
public List<List<String>> accountsMerge(List<List<String>> accounts) {
int n = accounts.size();
DSU dsu = new DSU(n);
Map<String, Integer> map = new HashMap<>(); // email -> index of acc
for(int i = 0; i < n; i++){
for(int j = 1; j < accounts.get(i).size(); j++){
String email = accounts.get(i).get(j);
String name = accounts.get(i).get(0);
if(!map.containsKey(email))
map.put(email, i);
else
dsu.union(i, map.get(email));
}
}
Map<Integer, List<String>> merged = new HashMap<>(); // index of acc -> list of emails
for(String email : map.keySet()){
int group = map.get(email);
int lead = dsu.find(group);
if(!merged.containsKey(lead))
merged.put(lead, new ArrayList<String>());
merged.get(lead).add(email);
}
List<List<String>> res = new ArrayList<>();
for(int ac : merged.keySet()){
List<String> grp = merged.get(ac);
Collections.sort(grp);
grp.add(0, accounts.get(ac).get(0));
res.add(grp);
}
return res;
}
}
class DSU {
int[] parent;
int[] rank;
public DSU(int size) {
rank = new int[size];
parent = new int[size];
for (int i = 0; i < size; i++)
parent[i] = i;
}
public int find(int x) {
if (parent[x] != x)
parent[x] = find(parent[x]);
return parent[x];
}
// Union By Rank
public boolean union(int x, int y) {
int xr = find(x), yr = find(y);
if (xr == yr) {
return false;
} else if (rank[xr] < rank[yr]) {
parent[xr] = yr;
} else if (rank[xr] > rank[yr]) {
parent[yr] = xr;
} else {
parent[yr] = xr;
rank[xr]++;
}
return true;
}
}