LeetCode 题解工作台
统计好子数组的数目
给你一个整数数组 nums 和一个整数 k ,请你返回 nums 中 好 子数组的数目。 一个子数组 arr 如果有 至少 k 对下标 (i, j) 满足 i 且 arr[i] == arr[j] ,那么称它是一个 好 子数组。 子数组 是原数组中一段连续 非空 的元素序列。 示例 1: 输入: n…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
如果一个子数组中包含 对相同的元素,那么这个子数组一定包含至少 对相同的元素。 我们用一个哈希表 统计窗口内数组元素出现的次数,用 统计窗口内相同元素的对数,用 维护窗口的左端点。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个整数数组 nums 和一个整数 k ,请你返回 nums 中 好 子数组的数目。
一个子数组 arr 如果有 至少 k 对下标 (i, j) 满足 i < j 且 arr[i] == arr[j] ,那么称它是一个 好 子数组。
子数组 是原数组中一段连续 非空 的元素序列。
示例 1:
输入:nums = [1,1,1,1,1], k = 10 输出:1 解释:唯一的好子数组是这个数组本身。
示例 2:
输入:nums = [3,1,4,3,2,2,4], k = 2 输出:4 解释:总共有 4 个不同的好子数组: - [3,1,4,3,2,2] 有 2 对。 - [3,1,4,3,2,2,4] 有 3 对。 - [1,4,3,2,2,4] 有 2 对。 - [4,3,2,2,4] 有 2 对。
提示:
1 <= nums.length <= 1051 <= nums[i], k <= 109
解题思路
方法一:哈希表 + 双指针
如果一个子数组中包含 对相同的元素,那么这个子数组一定包含至少 对相同的元素。
我们用一个哈希表 统计窗口内数组元素出现的次数,用 统计窗口内相同元素的对数,用 维护窗口的左端点。
遍历数组 ,我们将当前元素 作为右端点,那么窗口内相同元素的对数将增加 ,同时将 的出现次数加一,即 。接下来,我们循环判断移出左端点后窗口内相同元素的对数是否大于等于 ,如果大于等于 ,那么我们将左端点元素的出现次数减一,即 ,同时将窗口内相同元素的对数减去 ,即 ,同时将左端点右移,即 。此时窗口左端点以及左侧的所有元素都可以作为当前右端点的左端点,因此答案加上 。
最后,我们返回答案即可。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def countGood(self, nums: List[int], k: int) -> int:
cnt = Counter()
ans = cur = 0
i = 0
for x in nums:
cur += cnt[x]
cnt[x] += 1
while cur - cnt[nums[i]] + 1 >= k:
cnt[nums[i]] -= 1
cur -= cnt[nums[i]]
i += 1
if cur >= k:
ans += i + 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Candidates who use sliding window efficiently demonstrate understanding of optimal subarray searching techniques.
- question_mark
Look for solutions that maintain a hash table to track element frequencies for fast lookup and pair counting.
- question_mark
The ability to adjust the sliding window while maintaining the correct number of pairs is crucial for an optimal solution.
常见陷阱
外企场景- error
Not maintaining an efficient hash table can lead to a suboptimal solution.
- error
Misunderstanding the sliding window approach can cause incorrect counting of valid subarrays.
- error
Failing to properly adjust the window size when necessary can result in over-counting or under-counting subarrays.
进阶变体
外企场景- arrow_right_alt
Count the number of good subarrays with at least k pairs of equal elements, but with a modified constraint on array size.
- arrow_right_alt
Count good subarrays with exactly k pairs of equal elements, changing the requirement for the pair count.
- arrow_right_alt
Allow subarrays to be non-contiguous and count the pairs of equal elements in this modified scenario.