1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| class Solution { static int N = 20010; static int[] p = new int[N], sz = new int[N]; int ans = 1; int find(int x) { if (p[x] != x) p[x] = find(p[x]); return p[x]; } void union(int a, int b) { if (find(a) == find(b)) return ; sz[find(a)] += sz[find(b)]; p[find(b)] = p[find(a)]; ans = Math.max(ans, sz[find(a)]); } public int largestComponentSize(int[] nums) { int n = nums.length; Map<Integer, List<Integer>> map = new HashMap<>(); for (int i = 0; i < n; i++) { int cur = nums[i]; for (int j = 2; j * j <= cur; j++) { if (cur % j == 0) add(map, j, i); while (cur % j == 0) cur /= j; } if (cur > 1) add(map, cur, i); } for (int i = 0; i <= n; i++) { p[i] = i; sz[i] = 1; } for (int key : map.keySet()) { List<Integer> list = map.get(key); for (int i = 1; i < list.size(); i++) union(list.get(0), list.get(i)); } return ans; } void add(Map<Integer, List<Integer>> map, int key, int val) { List<Integer> list = map.getOrDefault(key, new ArrayList<>()); list.add(val); map.put(key, list); } }
|