-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0684-redundant-connection.cs
45 lines (36 loc) · 1.15 KB
/
0684-redundant-connection.cs
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
public class Solution {
public int[] FindRedundantConnection(int[][] edges) {
var nodes = edges.Length;
int[] parent = new int[nodes + 1];
int[] rank = new int[nodes + 1];
for(int i = 0; i < nodes; i++) {
parent[i] = i;
rank[i] = 1;
}
int findParent (int n) {
var p = parent[n];
while(p != parent[p]) {
parent[p] = parent[parent[p]];
p = parent[p];
}
return p;
}
bool union(int n1, int n2) {
(int p1, int p2) = (findParent(n1), findParent(n2));
if(p1 == p2) return false;
if(rank[p1] > rank[p2]) {
parent[p2] = p1;
rank[p1] += rank[p2];
} else {
parent[p1] = p2;
rank[p2] += rank[p1];
}
return true;
}
foreach(var edge in edges) {
if(union(edge[0], edge[1]) is false)
return edge;
}
return new int[2];
}
}