当前位置 博文首页 > 文章内容

    0952. Largest Component Size by Common Factor (H)

    作者: 栏目:未分类 时间:2020-08-31 11:00:27

    本站于2023年9月4日。收到“大连君*****咨询有限公司”通知
    说我们IIS7站长博客,有一篇博文用了他们的图片。
    要求我们给他们一张图片6000元。要不然法院告我们

    为避免不必要的麻烦,IIS7站长博客,全站内容图片下架、并积极应诉
    博文内容全部不再显示,请需要相关资讯的站长朋友到必应搜索。谢谢!

    另祝:版权碰瓷诈骗团伙,早日弃暗投明。

    相关新闻:借版权之名、行诈骗之实,周某因犯诈骗罪被判处有期徒刑十一年六个月

    叹!百花齐放的时代,渐行渐远!



    Largest Component Size by Common Factor (H)

    题目

    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
    

    Example 3:

    Input: [2,3,6,7,4,12,21,39]
    Output: 8
    

    Note:

    1. 1 <= A.length <= 20000
    2. 1 <= A[i] <= 100000

    题意

    给定一串正整数,将其中具有相同因数(>=2)的整数两两相连,求这样操作后最大连通分量中结点的数量。

    思路

    并查集处理。对于每一个整数,找到它所有大于2的因数,将该因数和整数本身添加到一个组中。最后统计每个组中数组中整数出现的次数即可。


    代码实现

    Java

    class Solution {
        public int largestComponentSize(int[] A) {
            int maxSize = 0, maxNum = 0;
            // 找到最大整数
            for (int num : A) {
                maxNum = Math.max(maxNum, num);
            }
    
            Map<Integer, Integer> map = new HashMap<>();
            int[] root = new int[maxNum + 1];
            for (int i = 1; i <= maxNum; i++) {
                root[i] = i;
            }
    
            for (int num : A) {
                for (int i = 2; i <= (int) Math.sqrt(num); i++) {
                    if (num % i == 0) {
                        int j = num / i;
                        union(root, num, i);
                        union(root, num, j);
                    }
                }
            }
    
            for (int num : A) {
                int tmp = findRoot(root, num);
                int size = map.getOrDefault(tmp, 0) + 1;
                map.put(tmp, size);
                maxSize = Math.max(maxSize, size);
            }
    
            return maxSize;
        }
    
        private void union(int[] root, int x, int y) {
            int rootX = findRoot(root, x), rootY = findRoot(root, y);
            if (rootX != rootY) {
                root[rootX] = rootY;
            }
        }
    
        private int findRoot(int[] root, int x) {
            // 路径压缩
            return root[x] == x ? x : (root[x] = findRoot(root, root[x]));
        }
    }