File tree Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change
1
+ class DSU (val n : Int ) {
2
+
3
+ val parent = IntArray (n) {it}
4
+ val rank = IntArray (n) {1 }
5
+
6
+ fun find (x : Int ): Int {
7
+ if (x != parent[x])
8
+ parent[x] = find(parent[x])
9
+ return parent[x]
10
+ }
11
+
12
+ fun union (x : Int , y : Int ): Boolean {
13
+ val pX = find(x)
14
+ val pY = find(y)
15
+
16
+ if (pX == pY)
17
+ return false
18
+
19
+ if (rank[pX] > rank[pY]) {
20
+ parent[pY] = pX
21
+ rank[pX] + = rank[pY]
22
+ } else {
23
+ parent[pX] = pY
24
+ rank[pY] + = rank[pX]
25
+ }
26
+
27
+ return true
28
+ }
29
+ }
30
+
31
+ class Solution {
32
+ fun accountsMerge (accounts : List <List <String >>): List <List <String >> {
33
+ val uf = DSU (accounts.size)
34
+ val emailToAcc = HashMap <String , Int >()
35
+
36
+ for ((i,accs) in accounts.withIndex()) {
37
+ for (j in 1 .. accs.lastIndex) {
38
+ val e = accs[j]
39
+ if (e in emailToAcc.keys) {
40
+ uf.union(i, emailToAcc[e]!! )
41
+ } else {
42
+ emailToAcc[e] = i
43
+ }
44
+ }
45
+ }
46
+
47
+ val emails = hashMapOf<Int , ArrayList <String >>()
48
+ for ((e, i) in emailToAcc) {
49
+ val main = uf.find(i)
50
+ emails[main] = emails.getOrDefault(main, ArrayList <String >()).apply { this .add(e) }
51
+ }
52
+
53
+ val res = ArrayList <ArrayList <String >>()
54
+ for ((i, em) in emails.entries) {
55
+ em.sort()
56
+ em.add(0 , accounts[i][0 ])
57
+ res.add(em)
58
+ }
59
+
60
+ return res
61
+ }
62
+ }
You can’t perform that action at this time.
0 commit comments