LeetCode 题解工作台
序列中不同最大公约数的数目
给你一个由正整数组成的数组 nums 。 数字序列的 最大公约数 定义为序列中所有整数的共有约数中的最大整数。 例如,序列 [4,6,16] 的最大公约数是 2 。 数组的一个 子序列 本质是一个序列,可以通过删除数组中的某些元素(或者不删除)得到。 例如, [2,5,10] 是 [1,2,1, 2…
4
题型
4
代码语言
3
相关题
当前训练重点
困难 · 数组·数学
答案摘要
对于数组 的所有子序列,其最大公约数一定不超过数组中的最大值 。 因此我们可以枚举 $[1,.. mx]$ 中的每个数 ,判断 是否为数组 的子序列的最大公约数,如果是,则答案加一。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个由正整数组成的数组 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 <= 1051 <= nums[i] <= 2 * 105
解题思路
方法一:枚举 + 数学
对于数组 的所有子序列,其最大公约数一定不超过数组中的最大值 。
因此我们可以枚举 中的每个数 ,判断 是否为数组 的子序列的最大公约数,如果是,则答案加一。
那么问题转换为:判断 是否为数组 的子序列的最大公约数。我们可以通过枚举 的倍数 ,判断 是否在数组 中,如果 在数组 中,则计算 的最大公约数 ,如果出现 ,则 是数组 的子序列的最大公约数。
时间复杂度 ,空间复杂度 。其中 和 分别是数组 的长度和数组 中的最大值。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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?