并查集:刷题必备神器
面试的时候,面试官出了一道并查集的算法题,辛亏以前复习过。写下这篇文章,加深自己的理解,同时希望帮助到正在准备面试的你。觉得好,可以收藏一波。
定义
动态维护若干个不重叠的集合,并支持合并与查询操作的一种数据结构。
下面以树作为并查集逻辑结构,具体代码实现使用数组。详细讲述并查集的初始化、合并和查询操作
并查集的初始化
开始各个节点的父元素均为自身,各个集合元素数量均为1
//并查集最大容纳元素个数
class UFS{
public int []arr;
//存储各个集合元素
public int [] number;
public UFS(int MAX_SIZE) {
public static int MAX_SIZE = 10000;
public static int arr[] = new int[MAX_SIZE];
//存储每个集合元素数量
public static int number[] = new int[MAX_SIZE];
}
public void init(){
for(int i = 0; i < arr.length; i++) arr[i] = i;
for(int i = 0; i < arr.length; i++) number[i] = 1;
}
}
并查集的查询操作
查询祖先节点,即属于哪个集合,查询的过程会进行路径压缩
//中间有路径压缩过程,可以细细分析一下
public int find(int x){
if(x != arr[x]) arr[x] = find(arr[x]);
return arr[x];
}
并查集的合并操作
合并两个集合,从逻辑结构来说,就是合并两棵子树
public void union(int x, int y) {
int xRoot = find(x);
int yRoot = find(y);
if(xRoot == yRoot) return;
if(arr[xRoot] > arr[yRoot]) {
arr[xRoot] += arr[yRoot];
arr[yRoot] = xRoot;
}else{
arr[yRoot] += arr[xRoot];
arr[xRoot] = yRoot;
}
}