这题是 LeetCode 952. Largest Component Size by Common Factor,经典 质因数分解 + 并查集(Union-Find) 解法,我直接给你可提交、最优、带注释的 Java 代码。
 
完整 Java 代码
 
java   
class Solution {
    static class UnionFind {
        int[] parent;
        int[] size;

        public UnionFind(int n) {
            parent = new int[n];
            size = new int[n];
            for (int i = 0; i < n; i++) {
                parent[i] = i;
                size[i] = 1;
            }
        }

        public int find(int x) {
            if (parent[x] != x) {
                parent[x] = find(parent[x]);
            }
            return parent[x];
        }

        public void union(int x, int y) {
            int fx = find(x);
            int fy = find(y);
            if (fx == fy) return;
            if (size[fx] < size[fy]) {
                parent[fx] = fy;
                size[fy] += size[fx];
            } else {
                parent[fy] = fx;
                size[fx] += size[fy];
            }
        }
    }

    public int largestComponentSize(int[] nums) {
        int max = 0;
        for (int num : nums) max = Math.max(max, num);
        UnionFind uf = new UnionFind(max + 1);

        for (int num : nums) {
            for (int k = 2; k * k <= num; k++) {
                if (num % k == 0) {
                    uf.union(num, k);
                    uf.union(num, num / k);
                }
            }
        }

        int[] cnt = new int[max + 1];
        int ans = 0;
        for (int num : nums) {
            int root = uf.find(num);
            cnt[root]++;
            ans = Math.max(ans, cnt[root]);
        }
        return ans;
    }
}
 
 
核心思路(一句话)
 
- 每个数 和它所有质因子连在一起
- 有公共质因子的数最终会在 同一个集合
- 最后统计哪个集合最大,就是答案
 
 
 
步骤极简版
 
1. 先求数组最大值,开对应大小的并查集。
2. 对每个数做质因数分解,把 数本身 和 每个质因子 合并。
3. 遍历所有数,找到它们的根,统计每个根出现次数。
4. 最大次数就是最大组件大小。
 
 
 
需要我给你:
 
- 时间/空间复杂度
- 更短的「面试背诵版」
- 或者 C++ / Python 版本?

 

Logo

欢迎加入DeepSeek 技术社区。在这里,你可以找到志同道合的朋友,共同探索AI技术的奥秘。

更多推荐