Created
November 2, 2021 02:24
-
-
Save tolinwei/a761b46802d2dc885544c31e208cabce to your computer and use it in GitHub Desktop.
Union & Find
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UnionFind { | |
int[] parent; | |
int[] rank; | |
public UnionFind(int n) { | |
parent = new int[n]; | |
rank = new int[n]; | |
for (int i = 0; i < n; i++) { | |
parent[i] = i; | |
} | |
} | |
// find the root of a | |
public int find(int a) { | |
// find with path compression, 从2ms提升到1ms | |
while (parent[a] != a) { | |
parent[a] = parent[parent[a]]; | |
a = parent[a]; | |
} | |
return a; | |
} | |
public void union(int a, int b) { | |
int rootA = find(a); | |
int rootB = find(b); | |
// union by rank | |
if (rootA == rootB) return; | |
if (rank[rootA] > rank[rootB]) { | |
parent[rootB] = rootA; | |
} else if (rank[rootA] < rank[rootB]) { | |
parent[rootA] = rootB; | |
} else { | |
parent[rootB] = rootA; | |
rank[rootA]++; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment