-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCode_04_UnionFind.java
More file actions
64 lines (55 loc) · 1.73 KB
/
Copy pathCode_04_UnionFind.java
File metadata and controls
64 lines (55 loc) · 1.73 KB
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
package algorithm.basic05;
import java.util.HashMap;
import java.util.List;
/**
* @Created by mood321
* @Date 2019/11/7 0007
* @Description TODO
*/
public class Code_04_UnionFind {
public static class UnionFindSet<K> {
public HashMap<K, K> fatherMap; // 本身元素和父节点
public HashMap<K, Integer> sizeMap;//节点 和节点个数
public UnionFindSet() {
fatherMap = new HashMap<K, K>();
sizeMap = new HashMap<K, Integer>();
}
public void makeSets(List<K> nodes) {
fatherMap.clear();
sizeMap.clear();
for (K node : nodes) {
fatherMap.put(node, node);
sizeMap.put(node, 1);
}
}
private K findHead(K node) {
K father = fatherMap.get(node);
if (father != node) {
father = findHead(father);
}
fatherMap.put(node, father);
return father;
}
public boolean isSameSet(K a, K b) {
return findHead(a) == findHead(b);
}
public void union(K a, K b) {
if (a == null || b == null) {
return;
}
K aHead = findHead(a);
K bHead = findHead(b);
if (aHead != bHead) {
int aSetSize= sizeMap.get(aHead);
int bSetSize = sizeMap.get(bHead);
if (aSetSize <= bSetSize) {
fatherMap.put(aHead, bHead);
sizeMap.put(bHead, aSetSize + bSetSize);
} else {
fatherMap.put(bHead, aHead);
sizeMap.put(aHead, aSetSize + bSetSize);
}
}
}
}
}