Skip to content

Commit 273a535

Browse files
authored
Create 0721-accounts-merge.kt
1 parent 9f69dd1 commit 273a535

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

kotlin/0721-accounts-merge.kt

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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+
}

0 commit comments

Comments
 (0)