Number of Operations to Make Network Connected LeetCode solution in Java

1
class Solution {
2
public int makeConnected(int n, int[][] connections) {
3
int m = connections.length;
4
if (m < n - 1) return -1;
5
UnionFind uf = new UnionFind(n);
6

7
for (int[] connection : connections) {
8
uf.union(connection[0], connection[1]);
9
}
10
return uf.getIsolated();
11
}
12
}
13

14
class UnionFind {
15
int[] root;
16
int[] rank;
17
int isolated;
18

19
public UnionFind(int n) {
20
root = new int[n];
21
rank = new int[n];
22
for (int i = 0; i < n; i++) {
23
root[i] = i;
24
rank[i] = 1;
25
}
26
isolated = 0;
27
}
28

29
public int find(int x) {
30
if (root[x] != x) root[x] = find(root[x]);
31
return root[x];
32
}
33

34
public void union(int x, int y) {
35
int rootx = find(x);
36
int rooty = find(y);
37
if (rootx == rooty) return;
38
if (rank[rootx] > rank[rooty]) {
39
root[rooty] = rootx;
40
} else if (rank[rootx] < rank[rooty]) {
41
root[rootx] = rooty;
42
} else {
43
root[rootx] = rooty;
44
rank[rooty] += 1;
45
}
46
}
47

48
public int getIsolated() {
49
for (int i = 0; i < root.length; i++) {
50
if (root[i] == i) isolated++;
51
}
52
return isolated - 1;
53
}
54
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0