-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnionFind.java
More file actions
43 lines (34 loc) · 839 Bytes
/
Copy pathUnionFind.java
File metadata and controls
43 lines (34 loc) · 839 Bytes
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
package Arrays;
public class UnionFind {
int size;
int[] parent;
int[] rank;
UnionFind(int n) {
size = n;
parent = new int[size];
rank = new int[size];
for (var i = 0; i < size ; i++) {
parent[i] = i;
rank[i] = 1;
}
}
public int find(int x) {
while (x != parent[x]) {
x = find(parent[x]);
}
return x;
}
public void union(int x, int y) {
int parentX = find(x);
int parentY = find(y);
if (parentX == parentY)
return;
if (rank[parentX] >= rank[parentY]) {
parent[parentY] = parentX;
rank[parentX] += rank[parentY];
} else {
parent[parentX] = parentY;
rank[parentY] += rank[parentX];
}
}
}