数据结构与算法分析章节
Java源码实现
public class DisjSets {
private int[] s = null;
public DisjSets(int num) {
s = new int[num];
for (int i = 0; i < num; i++)
s[i] = -1;
}
public void union(int root1, int root2) {
if (s[root2] < s[root1])// root2 is deeper
s[root1] = root2;
else {
if (s[root2] == s[root1])//Update height if same
s[root1]--;
s[root2] = root1;//Make root1 new root
}
}
public int find(int x){
if(s[x]<0)
return x;
else
return s[x]=find(s[x]);
}
}

本文介绍了一种使用Java实现的并查集数据结构。通过具体的源码展示了如何创建并查集,包括初始化、合并集合(union)以及查找根节点(find)等核心操作。此实现考虑了集合的高度平衡,确保了高效的性能。
1325

被折叠的 条评论
为什么被折叠?



