LeetCode 题解工作台
K 个不同整数的子数组
给定一个正整数数组 nums 和一个整数 k ,返回 nums 中 「 好子数组」 的数目。 如果 nums 的某个子数组中不同整数的个数恰好为 k ,则称 nums 的这个连续、不一定不同的子数组为 「 好子数组 」 。 例如, [1,2,3,1,2] 中有 3 个不同的整数: 1 , 2 ,以及…
4
题型
4
代码语言
3
相关题
当前训练重点
困难 · 数组·哈希·扫描
答案摘要
我们遍历数组 ,对于每个 ,我们需要找到最小的 ,使得 $nums[j_1], nums[j_1 + 1], \dots, nums[i]$ 中不同的整数个数小于等于 ,以及最小的 ,使得 $nums[j_2], nums[j_2 + 1], \dots, nums[i]$ 中不同的整数个数小于等于 。那么 $j_2 - j_1$ 就是以 结尾的满足条件的子数组的个数。 在实现上,我们定义一个函…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给定一个正整数数组 nums和一个整数 k,返回 nums 中 「好子数组」 的数目。
如果 nums 的某个子数组中不同整数的个数恰好为 k,则称 nums 的这个连续、不一定不同的子数组为 「好子数组 」。
- 例如,
[1,2,3,1,2]中有3个不同的整数:1,2,以及3。
子数组 是数组的 连续 部分。
示例 1:
输入:nums = [1,2,1,2,3], k = 2 输出:7 解释:恰好由 2 个不同整数组成的子数组:[1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].
示例 2:
输入:nums = [1,2,1,3,4], k = 3 输出:3 解释:恰好由 3 个不同整数组成的子数组:[1,2,1,3], [2,1,3], [1,3,4].
提示:
1 <= nums.length <= 2 * 1041 <= nums[i], k <= nums.length
解题思路
方法一:双指针
我们遍历数组 ,对于每个 ,我们需要找到最小的 ,使得 中不同的整数个数小于等于 ,以及最小的 ,使得 中不同的整数个数小于等于 。那么 就是以 结尾的满足条件的子数组的个数。
在实现上,我们定义一个函数 ,表示 中每个位置 对应的最小的 ,使得 中不同的整数个数小于等于 。该函数可以通过双指针实现,具体实现见代码。
然后我们调用 和 ,计算出每个位置对应的 和 ,然后计算出以每个位置 结尾的满足条件的子数组的个数,最后求和即可。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:
def f(k):
pos = [0] * len(nums)
cnt = Counter()
j = 0
for i, x in enumerate(nums):
cnt[x] += 1
while len(cnt) > k:
cnt[nums[j]] -= 1
if cnt[nums[j]] == 0:
cnt.pop(nums[j])
j += 1
pos[i] = j
return pos
return sum(a - b for a, b in zip(f(k - 1), f(k)))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Candidate efficiently uses sliding window and hash map for optimal subarray counting.
- question_mark
Understanding of counting subarrays with at most k distinct integers and leveraging this for exactly k.
- question_mark
Candidate implements efficient window size adjustments without unnecessary operations.
常见陷阱
外企场景- error
Failure to correctly adjust the window size when encountering more than k distinct integers.
- error
Mistaking the problem for one requiring brute-force enumeration of all subarrays, leading to a time complexity of O(n^2).
- error
Inaccurate handling of the edge case when the array contains fewer than k distinct integers.
进阶变体
外企场景- arrow_right_alt
Subarrays with at most k distinct integers.
- arrow_right_alt
Count subarrays where the number of distinct integers is exactly k, but with negative integers.
- arrow_right_alt
Subarrays with k distinct integers in a rotated array.