Skip to content

Commit df79c74

Browse files
authored
Update 952-largest-component-size-by-common-factor.js
1 parent 678025d commit df79c74

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

952-largest-component-size-by-common-factor.js

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,72 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
const largestComponentSize = function (nums) {
6+
const { sqrt } = Math
7+
const n = nums.length
8+
const uf = new UF(n)
9+
const primes = {}
10+
for (let i = 0; i < n; i++) {
11+
const num = nums[i]
12+
const prSet = primesSet(num)
13+
for (const e of prSet) {
14+
if (primes[e] == null) primes[e] = []
15+
primes[e].push(i)
16+
}
17+
}
18+
19+
const vals = Object.values(primes)
20+
for(const idxArr of vals) {
21+
const len = idxArr.length
22+
for(let i = 0; i < len - 1; i++) {
23+
uf.union(idxArr[i], idxArr[i + 1])
24+
}
25+
}
26+
let res = 0
27+
const hash = {}
28+
for(let i = 0; i < n; i++) {
29+
const root = uf.find(i)
30+
if(hash[root] == null) hash[root] = 0
31+
hash[root]++
32+
}
33+
return Math.max(...Object.values(hash))
34+
35+
function primesSet(n) {
36+
const limit = ~~(sqrt(n) + 1)
37+
for (let i = 2; i < limit; i++) {
38+
if (n % i === 0) {
39+
const res = primesSet(n / i)
40+
res.add(i)
41+
return res
42+
}
43+
}
44+
return new Set([n])
45+
}
46+
}
47+
48+
class UF {
49+
constructor(n) {
50+
this.root = Array(n)
51+
.fill(null)
52+
.map((_, i) => i)
53+
}
54+
find(x) {
55+
if (this.root[x] !== x) {
56+
this.root[x] = this.find(this.root[x])
57+
}
58+
return this.root[x]
59+
}
60+
union(x, y) {
61+
const xr = this.find(x)
62+
const yr = this.find(y)
63+
this.root[yr] = xr
64+
}
65+
}
66+
67+
// another
68+
69+
170
/**
271
* @param {number[]} A
372
* @return {number}

0 commit comments

Comments
 (0)