Description
You are given an integer array of unique positive integers nums. Consider the following graph:
There are nums.length nodes, labeled nums[0] to nums[nums.length - 1], There is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1. Return the size of the largest connected component in the graph.
Examples
Example 1:
Input: nums = [4,6,15,35] Output: 4
Example 2: Input: nums = [20,50,9,63] Output: 2
Example 3:
Input: nums = [2,3,6,7,4,12,21,39] Output: 8
Constraints:
1 <= nums.length <= $2 *
1
0
4
10^4
104 1 <= nums[i] <=
1
0
5
10^5
105 All the values of nums are unique.
思路
其实我看到的时候觉得要用并查集,但我按照
O
(
n
2
)
O(n^2)
O(n2)的时间复杂度去计算两两数值之间是否互素,虽然通过先执行findParent来提前剪枝,但还是会TTL
但时间复杂度还是太高了,去看了下discussion,应该的方法是找到nums中最大的值,然后建立 [0, 这个值] 的图,再通过遍历找到符合nums的数字,计算最终结果。
但我觉得两种方式还是各有优劣,就都放上来吧
代码
class Solution {
public boolean gcd(int a, int b) {
if (b == 0)
return a == 1;
return gcd(b, a % b);
}
public int findParent(int[] parents, int i) {
if (parents[i] != i)
parents[i] = findParent(parents, parents[i]);
return parents[i];
}
public void union(int[] parents, int[] rank, int i, int j) {
int parentI = findParent(parents, i);
int parentJ = findParent(parents, j);
int rankI = rank[parentI];
int rankJ = rank[parentJ];
if (parentI == parentJ)
return;
if (rankI > rankJ)
parents[parentJ] = parentI;
if (rankI < rankJ)
parents[parentI] = parentJ;
if (rankI == rankJ) {
parents[parentJ] = parentI;
rank[parentI] ++;
}
}
public int largestComponentSize(int[] nums) {
int[] parents = new int[nums.length];
int[] rank = new int[nums.length];
for (int i = 0; i < nums.length; i++)
parents[i] = i;
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (findParent(parents, i) != findParent(parents, j) && !gcd(nums[i], nums[j])) {
union(parents, rank, i, j);
}
}
}
int[] counts = new int[nums.length];
int max = 0;
for (int i = 0; i < nums.length; i++) {
counts[findParent(parents, i)] = counts[parents[i]] + 1;
max = Math.max(counts[parents[i]], max);
}
return max;
}
}
class Solution {
int[] p;
int get(int x){
return p[x]==x ? x : (p[x]=get(p[x])) ;
}
void add(int x, int y){
p[get(x)]=p[get(y)];
}
public int largestComponentSize(int[] A) {
int mx=0;
for(int i:A) mx=Math.max(i, mx);
p=new int[mx+1];
for(int i=1;i<=mx;++i) p[i]=i;
for(int i:A)
for(int j=(int)Math.sqrt(i);j>=2;--j)
if(i%j==0){
add(i, j);
add(i, i/j);
}
Map<Integer, Integer> map=new HashMap<Integer, Integer>();
int res=0;
for(int i:A){
int j=get(i);
if(!map.containsKey(j)) map.put(j, 1);
else map.put(j, map.get(j)+1);
res=Math.max(res, map.get(j));
}
return res;
}
}
|