LeetCode 题解工作台
最大公因数等于 K 的子数组数目
给你一个整数数组 nums 和一个整数 k ,请你统计并返回 nums 的子数组中元素的最大公因数等于 k 的子数组数目。 子数组 是数组中一个连续的非空序列。 数组的最大公因数 是能整除数组中所有元素的最大整数。 示例 1: 输入: nums = [9,3,1,2,6,3], k = 3 输出: …
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·数学
答案摘要
我们可以枚举 作为子数组的左端点,然后枚举 作为子数组的右端点,其中 $i \le j$。在枚举右端点的过程中,我们可以用一个变量 来维护当前子数组的最大公因数,每次枚举到一个新的右端点时,我们更新最大公因数 $g = \gcd(g, nums[j])$。如果 ,那么当前子数组的最大公因数等于 ,我们就将答案增加 。 枚举结束后,返回答案即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个整数数组 nums 和一个整数 k ,请你统计并返回 nums 的子数组中元素的最大公因数等于 k 的子数组数目。
子数组 是数组中一个连续的非空序列。
数组的最大公因数 是能整除数组中所有元素的最大整数。
示例 1:
输入:nums = [9,3,1,2,6,3], k = 3 输出:4 解释:nums 的子数组中,以 3 作为最大公因数的子数组如下: - [9,3,1,2,6,3] - [9,3,1,2,6,3] - [9,3,1,2,6,3] - [9,3,1,2,6,3]
示例 2:
输入:nums = [4], k = 7 输出:0 解释:不存在以 7 作为最大公因数的子数组。
提示:
1 <= nums.length <= 10001 <= nums[i], k <= 109
解题思路
方法一:直接枚举
我们可以枚举 作为子数组的左端点,然后枚举 作为子数组的右端点,其中 。在枚举右端点的过程中,我们可以用一个变量 来维护当前子数组的最大公因数,每次枚举到一个新的右端点时,我们更新最大公因数 。如果 ,那么当前子数组的最大公因数等于 ,我们就将答案增加 。
枚举结束后,返回答案即可。
时间复杂度 ,其中 和 分别是数组 的长度和数组 中的最大值。
class Solution:
def subarrayGCD(self, nums: List[int], k: int) -> int:
ans = 0
for i in range(len(nums)):
g = 0
for x in nums[i:]:
g = gcd(g, x)
ans += g == k
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate identifies that brute-force approach may not scale well and proposes optimizations.
- question_mark
Candidate suggests using sliding window technique for efficiency, ensuring correctness with GCD checks.
- question_mark
Candidate mentions mathematical insights into GCD that could simplify the problem or reduce unnecessary work.
常见陷阱
外企场景- error
Overlooking the need to calculate GCD for every subarray, leading to inefficiency.
- error
Failure to recognize when GCD exceeds k, causing unnecessary subarray checks.
- error
Confusing the greatest common divisor calculation with other operations, leading to incorrect results.
进阶变体
外企场景- arrow_right_alt
What if the array contains repeated elements? How does this affect GCD calculations?
- arrow_right_alt
How would the problem change if we had to check subarrays with GCD greater than k instead?
- arrow_right_alt
Consider handling edge cases like a single element array or when k is greater than any element.