-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Time: 367 ms (60.00%) | Memory: 68.3 MB (60.00%) - LeetSync
- Loading branch information
1 parent
9599e0c
commit cfd09b6
Showing
1 changed file
with
58 additions
and
0 deletions.
There are no files selected for viewing
58 changes: 58 additions & 0 deletions
58
2827-greatest-common-divisor-traversal/greatest-common-divisor-traversal.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
/** | ||
* @param {number[]} nums | ||
* @return {boolean} | ||
*/ | ||
var canTraverseAllPairs = function(nums) { | ||
const numElements = nums.length; | ||
if (numElements === 1) return true; | ||
|
||
const disjointSet = Array.from({ length: numElements }, (_, index) => index); | ||
const setSize = Array(numElements).fill(1); | ||
const factorFirstOccurrence = new Map(); | ||
|
||
function findSetLeader(x) { | ||
if (disjointSet[x] === x) return x; | ||
disjointSet[x] = findSetLeader(disjointSet[x]); | ||
return disjointSet[x]; | ||
} | ||
|
||
function unionSets(x, y) { | ||
const xLeader = findSetLeader(x); | ||
const yLeader = findSetLeader(y); | ||
if (xLeader === yLeader) return; | ||
if (setSize[xLeader] < setSize[yLeader]) { | ||
disjointSet[xLeader] = yLeader; | ||
setSize[yLeader] += setSize[xLeader]; | ||
} else { | ||
disjointSet[yLeader] = xLeader; | ||
setSize[xLeader] += setSize[yLeader]; | ||
} | ||
} | ||
|
||
for (let i = 0; i < numElements; i++) { | ||
let num = nums[i]; | ||
let divisor = 2; | ||
while (divisor * divisor <= num) { | ||
if (num % divisor === 0) { | ||
if (factorFirstOccurrence.has(divisor)) { | ||
unionSets(i, factorFirstOccurrence.get(divisor)); | ||
} else { | ||
factorFirstOccurrence.set(divisor, i); | ||
} | ||
while (num % divisor === 0) { | ||
num /= divisor; | ||
} | ||
} | ||
divisor++; | ||
} | ||
if (num > 1) { | ||
if (factorFirstOccurrence.has(num)) { | ||
unionSets(i, factorFirstOccurrence.get(num)); | ||
} else { | ||
factorFirstOccurrence.set(num, i); | ||
} | ||
} | ||
} | ||
|
||
return setSize[findSetLeader(0)] === numElements; | ||
}; |