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

Add JAVA solution for Question 323#488

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
neetcode-gh merged 1 commit intoneetcode-gh:mainfromhogo6002:patch-1
Jul 15, 2022
Merged
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
class Solution {
private int[] parent;
private int[] rank;

public int countComponents(int n, int[][] edges) {
parent = new int[n];
rank = new int[n];

for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 1;
}

int result = n;
for (int i = 0; i < edges.length; i++) {
if (union(edges[i][0], edges[i][1]) == 1) {
result--;
}
}

return result;
}

private int find(int node) {
int result = node;

while (parent[result] != result) {
parent[result] = parent[parent[result]];
result = parent[result];
}

return result;
}

private int union(int n1, int n2) {
int p1 = this.find(n1);
int p2 = this.find(n2);

if (p1 == p2) {
return 0;
}

if (rank[p2] > rank[p1]) {
parent[p1] = p2;
rank[p2] += rank[p1];
} else {
parent[p2] = p1;
rank[p1] += rank[p2];
}

return 1;
}
}

[8]ページ先頭

©2009-2025 Movatter.jp