|
| 1 | +// https://leetcode.com/problems/largest-component-size-by-common-factor |
| 2 | +// N = nums, M = max(N) |
| 3 | +// T: O(M + N sqrt(M) al(M) + N al(N)) al = inverse Ackermann function |
| 4 | +// S: O(M + N) |
| 5 | + |
| 6 | +import java.util.Arrays; |
| 7 | +import java.util.HashMap; |
| 8 | +import java.util.Map; |
| 9 | + |
| 10 | +public class LargestComponentSizeByCommonFactor { |
| 11 | + private static final class DisjointSet { |
| 12 | + private final int[] root, rank; |
| 13 | + |
| 14 | + public DisjointSet(int size) { |
| 15 | + root = new int[size]; |
| 16 | + rank = new int[size]; |
| 17 | + for (int i = 0 ; i < size ; i++) { |
| 18 | + root[i] = i; |
| 19 | + rank[i] = 1; |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + public int find(int num) { |
| 24 | + if (num == root[num]) { |
| 25 | + return num; |
| 26 | + } |
| 27 | + return root[num] = find(root[num]); |
| 28 | + } |
| 29 | + |
| 30 | + public boolean areConnected(int x, int y) { |
| 31 | + return find(x) == find(y); |
| 32 | + } |
| 33 | + |
| 34 | + public void union(int x, int y) { |
| 35 | + final int rootX = find(x), rootY = find(y); |
| 36 | + if (rootX == rootY) { |
| 37 | + return; |
| 38 | + } |
| 39 | + if (rank[rootX] > rank[rootY]) { |
| 40 | + root[rootY] = rootX; |
| 41 | + } else if (rank[rootX] < rank[rootY]) { |
| 42 | + root[rootY] = rootX; |
| 43 | + } else { |
| 44 | + root[rootY] = rootX; |
| 45 | + rank[rootX]++; |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + public int size() { |
| 50 | + return root.length; |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + public int largestComponentSize(int[] nums) { |
| 55 | + final int maxValue = Arrays.stream(nums).max().getAsInt(); |
| 56 | + final DisjointSet disjointSet = new DisjointSet(maxValue + 1); |
| 57 | + for (int number : nums) { |
| 58 | + for (int i = 2 ; i * i <= number ; i++) { |
| 59 | + if (number % i == 0) { |
| 60 | + disjointSet.union(number, i); |
| 61 | + disjointSet.union(number, number/ i); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + return largestComponentSize(disjointSet, nums); |
| 66 | + } |
| 67 | + |
| 68 | + private static int largestComponentSize(DisjointSet disjointSet, int[] numbers) { |
| 69 | + final Map<Integer, Integer> rootFrequencies = new HashMap<>(); |
| 70 | + int maxSize = 1; |
| 71 | + for (int number : numbers) { |
| 72 | + final int root = disjointSet.find(number); |
| 73 | + rootFrequencies.put(root, rootFrequencies.getOrDefault(root, 0) + 1); |
| 74 | + maxSize = Math.max(maxSize, rootFrequencies.get(root)); |
| 75 | + } |
| 76 | + return maxSize; |
| 77 | + } |
| 78 | +} |
0 commit comments