Created
July 19, 2020 03:17
-
-
Save arazmj/c0fc258f9855702561068d3683045245 to your computer and use it in GitHub Desktop.
This file contains 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 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