-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy path[tool]. UnionFind.java
executable file
·110 lines (91 loc) · 2.85 KB
/
[tool]. UnionFind.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
M
tags: Union Find, Lint
time: O(n), with Path Compression O(mN), with Union by Rank O(logN)
space: O(n)
#### Method1: Union Find with Array
- union(), find()
- Path Compresion: store skip father after found, which makes find O(1)
#### Method2: Union Find with HashMap
```
class Solution {
// Method1: Union Find with Array
class UnionFind {
int father[] = null;
int count;
public UnionFind(int n) {
father = new int[n];
for (int i = 0; i < n; i++) {
father[i] = i;
}
}
public void union(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX != rootY) {
father[rootX] = rootY;
count--;
}
}
// Alternative: union with rank[]
public void union(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX != rootY) {
if (rank[rootX] > rank[rootY]) {
father[rootY] = rootX;
} else if (rank[rootX] < rank[rootY]) {
father[rootX] = rootY;
} else { // rank[rootX] == rank[rootY]
father[rootY] = rootX;
rank[rootX]++;
}
count--;
}
}
public int query() {
return count;
}
public void setCount(int value) {
count = value;
}
private int find(int x) {
if (father[x] == x) return x; // found root father
return father[x] = find(father[x]);
}
}
// Method1: Union Find with HashMap
class UnionFind {
private HashMap<Integer, Integer> map = new HashMap<>();
/*
Model the disjoint set with 1D array
During initialization, assume each spot has itself as the parent
*/
public UnionFind(int size) {
for (int i = 0; i < size; i++) {
map.put(i, i);
}
}
/*
Use one key and find out the root parent of this set where they key belongs to.
*/
public int findRootParent(int item) {
int parent = map.get(item);
while (parent != map.get(parent)) {
parent = map.get(parent);
}
return parent;
}
/*
Find the root parent of each item. If the root parent is different,
join them together by adding them into the map as <key, value> pair.
*/
public void union(int itemX, int itemY) {
int parentX = findRootParent(itemX);
int parentY = findRootParent(itemY);
if (parentX != parentY) {
map.put(parentX, parentY);
}
}
}
}
```