- 定义一个并查集的类,并实现基本操作:
class UnionFind{
private Map<Integer,Integer> father;
public UnionFind(int n){
father = new HashMap<Integer,Integer>();
for(int i = 0;i < n;i++){
father.put(i,null);
}
}
public void add(int x){
if(!father.containesKey(x)){
father.put(x,null)
}
}
public int findFather(){
int root = x;
while(father.get(root)){
root = father.get(root)
}
while(x != root){
int original_father = father.get(x);
father.put(x,root)
x = original_father;
}
return root;
}
public void union(int x,int y){
int rootX = find(x)
int rootY = find(y)
if(rootX != rootY){
father.put(rootX,rootY)
}
}
public boolean isConnected(int x,int y){
return find(x) == find(y)
}
}
- 练习: LeetCode 128. 最长连续序列
使用并查集实现:
class UnionFind{
private Map<Integer,Integer> parent;
public UnionFind(int[] nums){
parent = new HashMap<>();
for(int num : nums){
parent.put(num,num)
}
}
public Integer find(int x){
if(!parent.containsKey(x)){
return null;
}
while(x != parent.get(x)){
parent.put(x,parent.get(parent.get(x)));
x = parent.get(x)
}
return x;
}
public void union(int x,int y){
int rootX = find(x)
int rootY = find(y)
if(rootX == rootY){
return;
}
parent.put(rootX,rootY)
}
}
class Solution{
public int longestConsecutive(int[] nums){
UnionFind uf = new UnionFind(nums);
int ans = 0;
for(int num : nums){
if(uf.find(num + 1) != null){
uf.union(num,num + 1)
}
}
for(int num : nums){
int right = uf.find(num)
ans = Math.max(ans,right - num + 1)
}
return ans;
}
}