Given a non-empty array of unique positive integers A
, consider the following graph:
- There are
A.length
nodes, labelledA[0]
toA[A.length - 1];
- There is an edge between
A[i]
andA[j]
if and only ifA[i]
andA[j]
share a common factor greater than 1.
Return the size of the largest connected component in the graph.
Example 1:
Input: [4,6,15,35]
Output: 4
Example 2:
Input: [20,50,9,63]
Output: 2
思路:用union find,father数组用prime factor 来进行union,再统计一下相同father的频率最大的set size返回。
class Solution {
private class UnionFind {
private int[] father;
public UnionFind(int n) {
this.father = new int[n+1];
for(int i = 0; i <= n; i++) {
father[i] = i;
}
}
public int find(int x) {
int j = x;
while(father[j] != j) {
j = father[j];
}
// path compression;
while(x != j) {
int fx = father[x];
father[x] = j;
x = fx;
}
return j;
}
public void union(int a, int b) {
int root_a = find(a);
int root_b = find(b);
if(root_a != root_b) {
father[root_a] = root_b;
}
}
}
public int largestComponentSize(int[] A) {
int n = A.length;
int maxvalue = 0;
for(Integer a: A) {
maxvalue = Math.max(maxvalue, a);
}
UnionFind uf = new UnionFind(maxvalue);
for(Integer a: A) {
for(int i = 2; i <= Math.sqrt(a); i++) {
if(a % i == 0) {
uf.union(a, i);
uf.union(a, a / i);
}
}
}
HashMap<Integer, Integer> hashmap = new HashMap<>();
int max = 0;
for(Integer a: A) {
int root_a = uf.find(a);
hashmap.put(root_a, hashmap.getOrDefault(root_a, 0) + 1);
max = Math.max(max, hashmap.get(root_a));
}
return max;
}
}