|
| 1 | +/** |
| 2 | + * 1998. GCD Sort of an Array |
| 3 | + * https://leetcode.com/problems/gcd-sort-of-an-array/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an integer array nums, and you can perform the following operation any |
| 7 | + * number of times on nums: |
| 8 | + * - Swap the positions of two elements nums[i] and nums[j] if gcd(nums[i], nums[j]) > 1 |
| 9 | + * where gcd(nums[i], nums[j]) is the greatest common divisor of nums[i] and nums[j]. |
| 10 | + * |
| 11 | + * Return true if it is possible to sort nums in non-decreasing order using the above swap |
| 12 | + * method, or false otherwise. |
| 13 | + */ |
| 14 | + |
| 15 | +/** |
| 16 | + * @param {number[]} nums |
| 17 | + * @return {boolean} |
| 18 | + */ |
| 19 | +var gcdSort = function(nums) { |
| 20 | + const maxNum = Math.max(...nums); |
| 21 | + const parent = new Array(maxNum + 1).fill().map((_, i) => i); |
| 22 | + const minPrime = new Array(maxNum + 1).fill(0); |
| 23 | + for (let i = 2; i <= maxNum; i++) { |
| 24 | + if (minPrime[i] === 0) { |
| 25 | + for (let j = i; j <= maxNum; j += i) { |
| 26 | + minPrime[j] = i; |
| 27 | + } |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + const groups = new Map(); |
| 32 | + for (const num of nums) { |
| 33 | + let curr = num; |
| 34 | + const primes = new Set(); |
| 35 | + while (curr > 1) { |
| 36 | + const prime = minPrime[curr]; |
| 37 | + primes.add(prime); |
| 38 | + curr /= prime; |
| 39 | + } |
| 40 | + for (const prime of primes) { |
| 41 | + if (!groups.has(prime)) groups.set(prime, []); |
| 42 | + groups.get(prime).push(num); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + for (const numbers of groups.values()) { |
| 47 | + for (let i = 1; i < numbers.length; i++) { |
| 48 | + union(numbers[i - 1], numbers[i], parent); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + const sorted = [...nums].sort((a, b) => a - b); |
| 53 | + for (let i = 0; i < nums.length; i++) { |
| 54 | + if (find(nums[i], parent) !== find(sorted[i], parent)) { |
| 55 | + return false; |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + return true; |
| 60 | + |
| 61 | + function find(x, parent) { |
| 62 | + if (parent[x] !== x) parent[x] = find(parent[x], parent); |
| 63 | + return parent[x]; |
| 64 | + } |
| 65 | + |
| 66 | + function union(x, y, parent) { |
| 67 | + parent[find(x, parent)] = find(y, parent); |
| 68 | + } |
| 69 | +}; |
0 commit comments