在计算机科学中,并查集是一种树型的数据结构,用于处理一些不交集(Disjoint Sets)的合并及查询问题。有一个联合-查找算法(union-find algorithm)定义了两个用于此数据结构的操作:
Find
:确定元素属于哪一个子集。它可以被用来确定两个元素是否属于同一子集。Union
:将两个子集合并成同一个集合。
----------------------------------------------------摘自维基百科
并查集,顾名思义,就是一个能合并查找的集合。最基本的并查集不会比链表效率好,所以有两种优化方式:
1、按秩合并。合并时,小的合并到大的上。
2、路径压缩。首次查找时,使路径上的节点指向根节点。
完整代码如下:
/**
* 并查集
*/
static class UnionFindSet {
//fatherMap的key为当前节点,value为父节点。sizeMap用来记录当前节点为头的长度
HashMap<Node, Node> fatherMap;
HashMap<Node, Integer> sizeMap;
static class Node {
int value;
public Node(int value) {
this.value = value;
}
}
//初始化,当前节点的父节点指向自己,长度设为1
public UnionFindSet(List<Node> nodes) {
fatherMap = new HashMap<>();
sizeMap = new HashMap<>();
for (Node node : nodes) {
fatherMap.put(node, node);
sizeMap.put(node, 1);
}
}
//获取当前节点的头节点,同时将当前节点及查找过程中经过的节点的父节点设为头节点
public Node getHead(Node node) {
Node father = fatherMap.get(node);
if (father != node) {
father = getHead(father);
}
fatherMap.put(node, father);
return father;
}
//判断两个节点是否在一个集合中,通过判断是否为同一个头节点。
public boolean isSameSet(Node node1, Node node2) {
return getHead(node1) == getHead(node2);
}
//联合两个节点所在集合,短的接到长的上。
public void union(Node node1, Node node2) {
Node head1 = getHead(node1);
Node head2 = getHead(node2);
int size1 = sizeMap.get(head1);
int size2 = sizeMap.get(head2);
if (size1 >= size2) {
fatherMap.put(head2, head1);
sizeMap.put(head1, size1 + size2);
}
}
}