-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathRedundant Connection.java
50 lines (46 loc) · 1.34 KB
/
Redundant Connection.java
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
// Runtime: 1 ms (Top 89.63%) | Memory: 43.5 MB (Top 75.35%)
class Solution {
public int[] findRedundantConnection(int[][] edges) {
UnionFind uf = new UnionFind(edges.length);
for (int[] edge : edges) {
if (!uf.union(edge[0], edge[1])) {
return new int[]{edge[0], edge[1]};
}
}
return null;
}
private class UnionFind {
int[] rank;
int[] root;
UnionFind(int n) {
rank = new int[n + 1];
root = new int[n + 1];
for (int i = 1; i <= n; i++) {
root[i] = i;
rank[i] = 1;
}
}
int find(int x) {
if (x == root[x]) {
return x;
}
return root[x] = find(root[x]);
}
boolean union(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX != rootY) {
if (rank[rootX] > rank[rootY]) {
root[rootY] = root[rootX];
} else if (rank[rootY] > rank[rootX]) {
root[rootX] = root[rootY];
} else {
root[rootY] = root[rootX];
rank[rootX]++;
}
return true;
}
return false;
}
}
}