Skip to content

Commit 2817bfe

Browse files
authored
Create 1998-gcd-sort-of-an-array.js
1 parent 0796005 commit 2817bfe

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

1998-gcd-sort-of-an-array.js

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {boolean}
4+
*/
5+
const gcdSort = function(nums) {
6+
const spf = Array(nums.length).fill(0)
7+
let maxNum = Math.max(...nums);
8+
sieve(maxNum);
9+
10+
const uf = new UnionFind(maxNum+1);
11+
for (let x of nums) {
12+
for (let f of getFactors(x)) uf.union(f, x);
13+
}
14+
15+
16+
const sortedArr = nums.slice();
17+
sortedArr.sort((a, b) => a - b)
18+
19+
for (let i = 0; i < nums.length; ++i) {
20+
let pu = uf.find(sortedArr[i]);
21+
let pv = uf.find(nums[i]);
22+
if (pu != pv) return false; // can't swap nums[i] with sortedArr[i]
23+
}
24+
return true;
25+
26+
function sieve( n) { // O(Nlog(logN)) ~ O(N)
27+
for (let i = 2; i <= n; ++i) spf[i] = i;
28+
for (let i = 2; i * i <= n; i++) {
29+
if (spf[i] != i) continue; // skip if `i` is not a prime number
30+
for (let j = i * i; j <= n; j += i) {
31+
if (spf[j] == j) { // marking spf[j] if it is not previously marked
32+
spf[j] = i;
33+
}
34+
}
35+
}
36+
}
37+
38+
function getFactors(n) { // O(logN)
39+
const factors = [];
40+
while (n > 1) {
41+
factors.push(spf[n]);
42+
n = ~~(n /spf[n]);
43+
}
44+
return factors;
45+
}
46+
};
47+
48+
function gcd( x, y) {
49+
return y == 0 ? x : gcd(y, x % y);
50+
}
51+
52+
class UnionFind {
53+
constructor(n) {
54+
this.parent = [];
55+
for (let i = 0; i < n; i++) this.parent[i] = i;
56+
}
57+
find(x) {
58+
if (x == this.parent[x]) return x;
59+
return this.parent[x] = this.find(this.parent[x]); // Path compression
60+
}
61+
union( u, v) {
62+
let pu = this.find(u), pv = this.find(v);
63+
if (pu != pv) this.parent[pu] = pv;
64+
}
65+
};
66+

0 commit comments

Comments
 (0)