Largest Component Size by Common Factor

Given a non-empty array of unique positive integers A, consider the following graph:

  • There are A.length nodes, labelled A[0] to A[A.length - 1];
  • There is an edge between A[i] and A[j] if and only if A[i] and A[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;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值