Skip to content

Commit d6b704b

Browse files
committed
Add solution #323
1 parent a8e403a commit d6b704b

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,7 @@
311311
320|[Generalized Abbreviation](./solutions/0320-generalized-abbreviation.js)|Medium|
312312
321|[Create Maximum Number](./solutions/0321-create-maximum-number.js)|Hard|
313313
322|[Coin Change](./solutions/0322-coin-change.js)|Medium|
314+
323|[Number of Connected Components in an Undirected Graph](./solutions/0323-number-of-connected-components-in-an-undirected-graph.js)|Medium|
314315
324|[Wiggle Sort II](./solutions/0324-wiggle-sort-ii.js)|Medium|
315316
326|[Power of Three](./solutions/0326-power-of-three.js)|Easy|
316317
327|[Count of Range Sum](./solutions/0327-count-of-range-sum.js)|Hard|
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* 323. Number of Connected Components in an Undirected Graph
3+
* https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/
4+
* Difficulty: Medium
5+
*
6+
* You have a graph of n nodes. You are given an integer n and an array edges where
7+
* edges[i] = [ai, bi] indicates that there is an edge between ai and bi in the graph.
8+
*
9+
* Return the number of connected components in the graph.
10+
*/
11+
12+
/**
13+
* @param {number} n
14+
* @param {number[][]} edges
15+
* @return {number}
16+
*/
17+
var countComponents = function(n, edges) {
18+
const parent = new Array(n).fill().map((_, i) => i);
19+
let components = n;
20+
21+
for (const [node1, node2] of edges) {
22+
union(node1, node2);
23+
}
24+
25+
return components;
26+
27+
function find(node) {
28+
if (parent[node] !== node) {
29+
parent[node] = find(parent[node]);
30+
}
31+
return parent[node];
32+
}
33+
34+
function union(node1, node2) {
35+
const root1 = find(node1);
36+
const root2 = find(node2);
37+
if (root1 !== root2) {
38+
parent[root1] = root2;
39+
components--;
40+
}
41+
}
42+
};

0 commit comments

Comments
 (0)