Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit fc1ae43

Browse files
authoredMar 22, 2025··
2685_Count_the_Number_of_Complete_Componets.java
1 parent 65e5d72 commit fc1ae43

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
 
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
// Problem Number: 2685
2+
3+
// Count the Number of Complete Components.
4+
5+
class UnionFind {
6+
public UnionFind(int n) {
7+
id = new int[n];
8+
rank = new int[n];
9+
nodeCount = new int[n];
10+
edgeCount = new int[n];
11+
for (int i = 0; i < n; ++i) {
12+
id[i] = i;
13+
nodeCount[i] = 1;
14+
}
15+
}
16+
17+
public void unionByRank(int u, int v) {
18+
final int i = find(u);
19+
final int j = find(v);
20+
++edgeCount[i];
21+
if (i == j)
22+
return;
23+
if (rank[i] < rank[j]) {
24+
id[i] = j;
25+
edgeCount[j] += edgeCount[i];
26+
nodeCount[j] += nodeCount[i];
27+
} else if (rank[i] > rank[j]) {
28+
id[j] = i;
29+
edgeCount[i] += edgeCount[j];
30+
nodeCount[i] += nodeCount[j];
31+
} else {
32+
id[i] = j;
33+
edgeCount[j] += edgeCount[i];
34+
nodeCount[j] += nodeCount[i];
35+
++rank[j];
36+
}
37+
}
38+
39+
public int find(int u) {
40+
return id[u] == u ? u : (id[u] = find(id[u]));
41+
}
42+
43+
public boolean isComplete(int u) {
44+
return nodeCount[u] * (nodeCount[u] - 1) / 2 == edgeCount[u];
45+
}
46+
47+
private int[] id;
48+
private int[] rank;
49+
private int[] nodeCount;
50+
private int[] edgeCount;
51+
}
52+
53+
class Solution {
54+
public int countCompleteComponents(int n, int[][] edges) {
55+
int ans = 0;
56+
UnionFind uf = new UnionFind(n);
57+
Set<Integer> parents = new HashSet<>();
58+
59+
for (int[] edge : edges) {
60+
final int u = edge[0];
61+
final int v = edge[1];
62+
uf.unionByRank(u, v);
63+
}
64+
65+
for (int i = 0; i < n; ++i) {
66+
final int parent = uf.find(i);
67+
if (parents.add(parent) && uf.isComplete(parent))
68+
++ans;
69+
}
70+
71+
return ans;
72+
}
73+
}

0 commit comments

Comments
 (0)
Please sign in to comment.