-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickFindUF.java
More file actions
45 lines (37 loc) · 948 Bytes
/
QuickFindUF.java
File metadata and controls
45 lines (37 loc) · 948 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
44
45
package UnionFind;
public class QuickFindUF {
private int[] id;
private int count;
public QuickFindUF(int n) {
id = new int[n];
count = n;
for (int i = 0; i < n; i++) {
id[i] = i;
}
}
public int find(int p) {
validate(p);
return id[p];
}
public boolean connected(int p, int q) {
validate(p);
validate(q);
return id[p] == id[q];
}
public void union(int p, int q) {
int pID = id[p], qID = id[q];
if (pID == qID) return;
for (int i = 0; i < id.length; i++) {
if (id[i] == pID) {
id[i] = qID;
}
}
count--;
}
private void validate(int p) {
int n = id.length;
if (p < 0 || p >= n) {
throw new IllegalArgumentException("element " + p + " is out of range");
}
}
}