Skip to content

Instantly share code, notes, and snippets.

@tolinwei
Created November 2, 2021 02:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tolinwei/a761b46802d2dc885544c31e208cabce to your computer and use it in GitHub Desktop.
Save tolinwei/a761b46802d2dc885544c31e208cabce to your computer and use it in GitHub Desktop.
Union & Find
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