LeetCode 题解工作台

序列中不同最大公约数的数目

给你一个由正整数组成的数组 nums 。 数字序列的 最大公约数 定义为序列中所有整数的共有约数中的最大整数。 例如,序列 [4,6,16] 的最大公约数是 2 。 数组的一个 子序列 本质是一个序列,可以通过删除数组中的某些元素(或者不删除)得到。 例如, [2,5,10] 是 [1,2,1, 2…

category

4

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

困难 · 数组·数学

bolt

答案摘要

对于数组 的所有子序列,其最大公约数一定不超过数组中的最大值 。 因此我们可以枚举 $[1,.. mx]$ 中的每个数 ,判断 是否为数组 的子序列的最大公约数,如果是,则答案加一。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个由正整数组成的数组 nums

数字序列的 最大公约数 定义为序列中所有整数的共有约数中的最大整数。

  • 例如,序列 [4,6,16] 的最大公约数是 2

数组的一个 子序列 本质是一个序列,可以通过删除数组中的某些元素(或者不删除)得到。

  • 例如,[2,5,10][1,2,1,2,4,1,5,10] 的一个子序列。

计算并返回 nums 的所有 非空 子序列中 不同 最大公约数的 数目

 

示例 1:

输入:nums = [6,10,3]
输出:5
解释:上图显示了所有的非空子序列与各自的最大公约数。
不同的最大公约数为 6 、10 、3 、2 和 1 。

示例 2:

输入:nums = [5,15,40,5,6]
输出:7

 

提示:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 2 * 105
lightbulb

解题思路

方法一:枚举 + 数学

对于数组 numsnums 的所有子序列,其最大公约数一定不超过数组中的最大值 mxmx

因此我们可以枚举 [1,..mx][1,.. mx] 中的每个数 xx,判断 xx 是否为数组 numsnums 的子序列的最大公约数,如果是,则答案加一。

那么问题转换为:判断 xx 是否为数组 numsnums 的子序列的最大公约数。我们可以通过枚举 xx 的倍数 yy,判断 yy 是否在数组 numsnums 中,如果 yy 在数组 numsnums 中,则计算 yy 的最大公约数 gg,如果出现 g=xg = x,则 xx 是数组 numsnums 的子序列的最大公约数。

时间复杂度 O(n+M×logM)O(n + M \times \log M),空间复杂度 O(M)O(M)。其中 nnMM 分别是数组 numsnums 的长度和数组 numsnums 中的最大值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
    def countDifferentSubsequenceGCDs(self, nums: List[int]) -> int:
        mx = max(nums)
        vis = set(nums)
        ans = 0
        for x in range(1, mx + 1):
            g = 0
            for y in range(x, mx + 1, x):
                if y in vis:
                    g = gcd(g, y)
                    if g == x:
                        ans += 1
                        break
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Ability to optimize solutions using number theory principles.

  • question_mark

    Efficiency in handling large input sizes and array lengths.

  • question_mark

    Understanding of dynamic programming or optimization strategies.

warning

常见陷阱

外企场景
  • error

    Attempting to brute-force through all subsequences without leveraging mathematical properties.

  • error

    Overlooking optimizations related to divisibility and GCD calculation.

  • error

    Not handling large input sizes efficiently, leading to time limit exceeded errors.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    How does the problem change if we are given an array of size 10^6?

  • arrow_right_alt

    What if the array only contains powers of two?

  • arrow_right_alt

    How does the problem behave with very large numbers up to 2 * 10^5?

help

常见问题

外企场景

序列中不同最大公约数的数目题解:数组·数学 | LeetCode #1819 困难