Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit0e644d6

Browse files
authored
Merge pull requestneetcode-gh#488 from hogo6002/patch-1
Add JAVA solution for Question 323
2 parentse8fdc3d +31cec75 commit0e644d6

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
classSolution {
2+
privateint[]parent;
3+
privateint[]rank;
4+
5+
publicintcountComponents(intn,int[][]edges) {
6+
parent =newint[n];
7+
rank =newint[n];
8+
9+
for (inti =0;i <n;i++) {
10+
parent[i] =i;
11+
rank[i] =1;
12+
}
13+
14+
intresult =n;
15+
for (inti =0;i <edges.length;i++) {
16+
if (union(edges[i][0],edges[i][1]) ==1) {
17+
result--;
18+
}
19+
}
20+
21+
returnresult;
22+
}
23+
24+
privateintfind(intnode) {
25+
intresult =node;
26+
27+
while (parent[result] !=result) {
28+
parent[result] =parent[parent[result]];
29+
result =parent[result];
30+
}
31+
32+
returnresult;
33+
}
34+
35+
privateintunion(intn1,intn2) {
36+
intp1 =this.find(n1);
37+
intp2 =this.find(n2);
38+
39+
if (p1 ==p2) {
40+
return0;
41+
}
42+
43+
if (rank[p2] >rank[p1]) {
44+
parent[p1] =p2;
45+
rank[p2] +=rank[p1];
46+
}else {
47+
parent[p2] =p1;
48+
rank[p1] +=rank[p2];
49+
}
50+
51+
return1;
52+
}
53+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp