LeetCode 题解工作台

按公因数计算最大组件大小

给定一个由不同正整数的组成的非空数组 nums ,考虑下面的图: 有 nums.length 个节点,按从 nums[0] 到 nums[nums.length - 1] 标记; 只有当 nums[i] 和 nums[j] 共用一个大于 1 的公因数时, nums[i] 和 nums[j] 之间才有…

category

5

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

困难 · 数组·哈希·扫描

bolt

答案摘要

利用“试除法”,对 中的每个数 分解因数,然后将每个因数 与 合并,$v / i$ 与 合并。此过程用并查集来维护连通分量。 最后,遍历 中每个数 ,找出所在的连通分量,出现次数最多的连通分量就是所求的答案。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个由不同正整数的组成的非空数组 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 中所有值都 不同
lightbulb

解题思路

方法一:数学 + 并查集

利用“试除法”,对 numsnums 中的每个数 vv 分解因数,然后将每个因数 iivv 合并,v/iv / ivv 合并。此过程用并查集来维护连通分量。

最后,遍历 numsnums 中每个数 vv,找出所在的连通分量,出现次数最多的连通分量就是所求的答案。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class UnionFind:
    def __init__(self, n):
        self.p = list(range(n))

    def union(self, a, b):
        pa, pb = self.find(a), self.find(b)
        if pa != pb:
            self.p[pa] = pb

    def find(self, x):
        if self.p[x] != x:
            self.p[x] = self.find(self.p[x])
        return self.p[x]


class Solution:
    def largestComponentSize(self, nums: List[int]) -> int:
        uf = UnionFind(max(nums) + 1)
        for v in nums:
            i = 2
            while i <= v // i:
                if v % i == 0:
                    uf.union(v, i)
                    uf.union(v, v // i)
                i += 1
        return max(Counter(uf.find(v) for v in nums).values())
speed

复杂度分析

指标
时间complexity depends on factorization and union-find operations, roughly O(N sqrt(M)) where N is array length and M is max value. Space complexity is O(N + M) for parent and factor maps. Optimizations like path compression help maintain near-linear performance.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate attempts naive pairwise GCD checks, which is inefficient for large inputs.

  • question_mark

    Candidate successfully maps numbers to prime factors, indicating understanding of factor-based graph structure.

  • question_mark

    Candidate applies union-find with path compression or other optimizations to manage large component merging efficiently.

warning

常见陷阱

外企场景
  • error

    Trying to compare every pair with GCD, causing TLE on large arrays.

  • error

    Forgetting to merge all numbers sharing a factor, leading to undercounting component sizes.

  • error

    Neglecting path compression, resulting in slower union-find operations and exceeding time limits.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Compute largest component size considering only prime numbers in the array.

  • arrow_right_alt

    Find the number of connected components rather than the largest size using the same factor-based graph.

  • arrow_right_alt

    Determine largest component size when edges exist for numbers sharing any divisor within a given threshold, not necessarily prime factors.

help

常见问题

外企场景

按公因数计算最大组件大小题解:数组·哈希·扫描 | LeetCode #952 困难