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

Commit b3038c3

Browse files
Create 3378-count-connected-components-in-lcm-graph.js
1 parent 39a0d13 commit b3038c3

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} threshold
4+
* @return {number}
5+
*/
6+
var countComponents = function(nums, threshold) {
7+
const dsu = new DSU(threshold);
8+
const n = nums.length;
9+
let res = 0;
10+
11+
for (let i = 0; i < nums.length; i++) {
12+
if (nums[i] <= threshold) {
13+
for (let j = nums[i]; j <= threshold; j += nums[i]) {
14+
dsu.join(nums[i], j);
15+
}
16+
}
17+
}
18+
19+
const st = new Set();
20+
for (let i = 0; i < nums.length; i++) {
21+
if (nums[i] > threshold) res++;
22+
else st.add(dsu.findParent(nums[i]));
23+
}
24+
25+
res += st.size;
26+
return res;
27+
};
28+
class DSU {
29+
constructor(n) {
30+
this.parent = new Array(n + 1).fill(-1);
31+
}
32+
33+
findParent(x) {
34+
if (this.parent[x] === -1) return x;
35+
return this.parent[x] = this.findParent(this.parent[x]);
36+
}
37+
38+
join(x, y) {
39+
const X = this.findParent(x);
40+
const Y = this.findParent(y);
41+
if (X === Y) return false;
42+
this.parent[X] = Y;
43+
return true;
44+
}
45+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /