File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ fun findRedundantConnection (edges : Array <IntArray >): IntArray {
3
+ val uf = UnionFind (edges.size)
4
+
5
+ for (edge in edges) {
6
+ val (u, v) = edge
7
+
8
+ if (uf.isConnected(u- 1 , v- 1 ))
9
+ return intArrayOf(u, v)
10
+
11
+ uf.unify(u- 1 , v- 1 )
12
+ }
13
+
14
+ return intArrayOf(0 )
15
+ }
16
+ }
17
+
18
+ class UnionFind (n : Int ) {
19
+ val parent = IntArray (n) { it }
20
+ val rank = IntArray (n) { 1 }
21
+
22
+ fun unify (p : Int , q : Int ) {
23
+ val rootP = find(p)
24
+ val rootQ = find(q)
25
+
26
+ if (rootP == rootQ)
27
+ return
28
+
29
+ if (rank[rootP] > rank[rootQ]) {
30
+ parent[rootQ] = parent[rootP]
31
+ rank[rootP] + = rank[rootQ]
32
+ } else {
33
+ parent[rootP] = parent[rootQ]
34
+ rank[rootQ] + = rank[rootP]
35
+ }
36
+ }
37
+
38
+ fun find (p : Int ): Int {
39
+ var root = p
40
+ var curr = p
41
+
42
+ while (root != parent[root])
43
+ root = parent[root]
44
+
45
+ while (root != curr) {
46
+ val next = parent[curr]
47
+ parent[p] = parent[root]
48
+ curr = next
49
+ }
50
+
51
+ return root
52
+ }
53
+
54
+ fun isConnected (p : Int , q : Int ): Boolean {
55
+ return find(p) == find(q)
56
+ }
57
+ }
You can’t perform that action at this time.
0 commit comments