LeetCode 题解工作台
含最多 K 个可整除元素的子数组
给你一个整数数组 nums 和两个整数 k 和 p ,找出并返回满足要求的不同的子数组数,要求子数组中最多 k 个可被 p 整除的元素。 如果满足下述条件之一,则认为数组 nums1 和 nums2 是 不同 数组: 两数组长度 不同 ,或者 存在 至少 一个下标 i 满足 nums1[i] != …
6
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们可以枚举子数组的左端点 ,再在 $[i, n)$ 的范围内枚举子数组的右端点 ,在枚举右端点的过程中,我们通过双哈希的方式,将子数组的哈希值存入集合中,最后返回集合的大小即可。 时间复杂度 ,空间复杂度 。其中 为数组的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个整数数组 nums 和两个整数 k 和 p ,找出并返回满足要求的不同的子数组数,要求子数组中最多 k 个可被 p 整除的元素。
如果满足下述条件之一,则认为数组 nums1 和 nums2 是 不同 数组:
- 两数组长度 不同 ,或者
- 存在 至少 一个下标
i满足nums1[i] != nums2[i]。
子数组 定义为:数组中的连续元素组成的一个 非空 序列。
示例 1:
输入:nums = [2,3,3,2,2], k = 2, p = 2 输出:11 解释: 位于下标 0、3 和 4 的元素都可以被 p = 2 整除。 共计 11 个不同子数组都满足最多含 k = 2 个可以被 2 整除的元素: [2]、[2,3]、[2,3,3]、[2,3,3,2]、[3]、[3,3]、[3,3,2]、[3,3,2,2]、[3,2]、[3,2,2] 和 [2,2] 。 注意,尽管子数组 [2] 和 [3] 在 nums 中出现不止一次,但统计时只计数一次。 子数组 [2,3,3,2,2] 不满足条件,因为其中有 3 个元素可以被 2 整除。
示例 2:
输入:nums = [1,2,3,4], k = 4, p = 1 输出:10 解释: nums 中的所有元素都可以被 p = 1 整除。 此外,nums 中的每个子数组都满足最多 4 个元素可以被 1 整除。 因为所有子数组互不相同,因此满足所有限制条件的子数组总数为 10 。
提示:
1 <= nums.length <= 2001 <= nums[i], p <= 2001 <= k <= nums.length
进阶:
你可以设计并实现时间复杂度为 O(n2) 的算法解决此问题吗?
解题思路
方法一:枚举 + 字符串哈希
我们可以枚举子数组的左端点 ,再在 的范围内枚举子数组的右端点 ,在枚举右端点的过程中,我们通过双哈希的方式,将子数组的哈希值存入集合中,最后返回集合的大小即可。
时间复杂度 ,空间复杂度 。其中 为数组的长度。
class Solution:
def countDistinct(self, nums: List[int], k: int, p: int) -> int:
s = set()
n = len(nums)
base1, base2 = 131, 13331
mod1, mod2 = 10**9 + 7, 10**9 + 9
for i in range(n):
h1 = h2 = cnt = 0
for j in range(i, n):
cnt += nums[j] % p == 0
if cnt > k:
break
h1 = (h1 * base1 + nums[j]) % mod1
h2 = (h2 * base2 + nums[j]) % mod2
s.add(h1 << 32 | h2)
return len(s)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on how many subarrays are generated and hashed, potentially O(n^2) in worst-case enumeration. Space complexity depends on the storage of distinct subarrays in a hash set or trie, which can grow proportional to the number of unique subarrays. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Focus on counting subarrays with constraints on divisible elements rather than total subarrays.
- question_mark
Ask about strategies to avoid counting duplicates efficiently using hashing.
- question_mark
Consider how to stop subarray expansion early when constraints are violated.
常见陷阱
外企场景- error
Failing to count only distinct subarrays and double-counting repeated sequences.
- error
Continuing to extend subarrays after the divisible element count exceeds k.
- error
Using inefficient comparison methods for subarray uniqueness instead of hashing.
进阶变体
外企场景- arrow_right_alt
Count subarrays where exactly k elements are divisible by p instead of at most k.
- arrow_right_alt
Allow subarrays of fixed length and count those meeting the divisible constraint.
- arrow_right_alt
Compute the total sum of elements in subarrays with at most k divisible elements.