|
| 1 | +/** |
| 2 | + * 952. Largest Component Size by Common Factor |
| 3 | + * https://leetcode.com/problems/largest-component-size-by-common-factor/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an integer array of unique positive integers nums. Consider the following graph: |
| 7 | + * - There are nums.length nodes, labeled nums[0] to nums[nums.length - 1], |
| 8 | + * - There is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common |
| 9 | + * factor greater than 1. |
| 10 | + * |
| 11 | + * Return the size of the largest connected component in the graph. |
| 12 | + */ |
| 13 | + |
| 14 | +/** |
| 15 | + * @param {number[]} nums |
| 16 | + * @return {number} |
| 17 | + */ |
| 18 | +var largestComponentSize = function(nums) { |
| 19 | + const max = Math.max(...nums); |
| 20 | + const parent = new Array(max + 1).fill().map((_, i) => i); |
| 21 | + const rank = new Array(max + 1).fill(0); |
| 22 | + |
| 23 | + for (const num of nums) { |
| 24 | + for (let factor = 2; factor * factor <= num; factor++) { |
| 25 | + if (num % factor === 0) { |
| 26 | + union(parent, rank, num, factor); |
| 27 | + union(parent, rank, num, num / factor); |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + const map = new Map(); |
| 33 | + let result = 0; |
| 34 | + |
| 35 | + for (const num of nums) { |
| 36 | + const root = find(parent, num); |
| 37 | + map.set(root, (map.get(root) || 0) + 1); |
| 38 | + result = Math.max(result, map.get(root)); |
| 39 | + } |
| 40 | + |
| 41 | + return result; |
| 42 | + |
| 43 | + function find(parent, x) { |
| 44 | + if (parent[x] !== x) { |
| 45 | + parent[x] = find(parent, parent[x]); |
| 46 | + } |
| 47 | + return parent[x]; |
| 48 | + } |
| 49 | + |
| 50 | + function union(parent, rank, x, y) { |
| 51 | + const rootX = find(parent, x); |
| 52 | + const rootY = find(parent, y); |
| 53 | + if (rootX !== rootY) { |
| 54 | + if (rank[rootX] < rank[rootY]) { |
| 55 | + parent[rootX] = rootY; |
| 56 | + } else if (rank[rootX] > rank[rootY]) { |
| 57 | + parent[rootY] = rootX; |
| 58 | + } else { |
| 59 | + parent[rootY] = rootX; |
| 60 | + rank[rootX]++; |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | +}; |
0 commit comments