-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0684-redundant-connection.kt
57 lines (44 loc) · 1.19 KB
/
0684-redundant-connection.kt
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
class Solution {
fun findRedundantConnection(edges: Array<IntArray>): IntArray {
val uf = UnionFind(edges.size)
for (edge in edges) {
val (u, v) = edge
if (uf.isConnected(u-1, v-1))
return intArrayOf(u, v)
uf.unify(u-1, v-1)
}
return intArrayOf(0)
}
}
class UnionFind(n : Int) {
val parent = IntArray(n) { it }
val rank = IntArray(n) { 1 }
fun unify(p: Int, q: Int) {
val rootP = find(p)
val rootQ = find(q)
if (rootP == rootQ)
return
if (rank[rootP] > rank[rootQ]) {
parent[rootQ] = parent[rootP]
rank[rootP] += rank[rootQ]
} else {
parent[rootP] = parent[rootQ]
rank[rootQ] += rank[rootP]
}
}
fun find(p: Int): Int {
var root = p
var curr = p
while (root != parent[root])
root = parent[root]
while (root != curr) {
val next = parent[curr]
parent[p] = parent[root]
curr = next
}
return root
}
fun isConnected(p: Int, q: Int): Boolean {
return find(p) == find(q)
}
}