力扣刷题打开03 按公因数计算最大组件大小(困难)

题目:

给定一个由不同正整数的组成的非空数组 nums ,考虑下面的图:

有 nums.length 个节点,按从 nums[0] 到 nums[nums.length - 1] 标记;
只有当 nums[i] 和 nums[j] 共用一个大于 1 的公因数时,nums[i] 和 nums[j]之间才有一条边。
返回 图中最大连通组件的大小 。

示例 1:

输入:nums = [4,6,15,35]
输出:4
示例 2:

输入:nums = [20,50,9,63]
输出:2
示例 3:

输入:nums = [2,3,6,7,4,12,21,39]
输出:8
 

提示:

1 <= nums.length <= 2 * 104
1 <= nums[i] <= 105
nums 中所有值都 不同

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/largest-component-size-by-common-factor
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

答案:

class Solution {

    public int largestComponentSize(int[] nums) {

        int m = Arrays.stream(nums).max().getAsInt();

        //将数组转化为流——最大值——作为Int类型的数据赋值给m

        UnionFind uf = new UnionFind(m + 1);//并查集类型(下面会定义)

        //并查集,将两个数组合并,询问两个元素是否在一个集合里

        for (int num : nums) {//等同于for(int num=num.begin();num<=nums.end();num++)

            for (int i = 2; i*i <= num; i++) {

                if (num % i == 0) {

                    uf.union(num, i);//union()连接两结点

                    uf.union(num, num / i);

                }

            }

        }

        int[] counts = new int[m + 1];

        int ans = 0;

        for (int num : nums) {

            int root = uf.find(num);//查找父节点

            counts[root]++;

            ans = Math.max(ans, counts[root]);

        }

        return ans;

    }

}

class UnionFind {

    int[] parent;

    int[] rank;

    public UnionFind(int n) {

        parent = new int[n];

        for (int i = 0; i < n; i++) {

            parent[i] = i;

        }

        rank = new int[n];

    }

    public void union(int x, int y) {

        int rootx = find(x);

        int rooty = find(y);

        if (rootx != rooty) {

            if (rank[rootx] > rank[rooty]) {

                parent[rooty] = rootx;

            } else if (rank[rootx] < rank[rooty]) {

                parent[rootx] = rooty;

            } else {

                parent[rooty] = rootx;

                rank[rootx]++;

            }

        }

    }

    public int find(int x) {

        if (parent[x] != x) {

            parent[x] = find(parent[x]);

        }

        return parent[x];

    }

}

结论:

不会写...希望未来能有一天敲出来吧...

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值