Skip to content

Instantly share code, notes, and snippets.

@arazmj
Created July 19, 2020 03:17
Show Gist options
  • Save arazmj/c0fc258f9855702561068d3683045245 to your computer and use it in GitHub Desktop.
Save arazmj/c0fc258f9855702561068d3683045245 to your computer and use it in GitHub Desktop.
class Solution {
int[] p;
int[] r;
int c = 0;
public int countComponents1(int n, int[][] edges) {
p = new int[n];
r = new int[n];
for (int i = 0; i < n; i++) {
p[i] = i;
}
for (int[] edge: edges) {
union(edge[0], edge[1]);
}
Set<Integer> set = new HashSet<>();
for (int e: p)
set.add(find(e));
return set.size();
}
private int find(int x) {
if (p[x] != x)
p[x] = find(p[x]);
return p[x];
}
private void union(int x, int y) {
int fx = find(x);
int fy = find(y);
if (r[fx] < r[fy]) {
p[fx] = fy;
} else if (r[fx] > r[fy]) {
p[fy] = fx;
} else {
p[fx] = fy;
r[fx]++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment