|
| 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