LeetCode 题解工作台
大小为 K 且平均值大于等于阈值的子数组数目
给你一个整数数组 arr 和两个整数 k 和 threshold 。 请你返回长度为 k 且平均值大于等于 threshold 的子数组数目。 示例 1: 输入: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4 输出: 3 解释: 子数组 [2,5,5],…
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 滑动窗口(状态滚动更新)
答案摘要
不妨将 `threshold` 乘以 ,这样我们就可以直接比较窗口内的和与 `threshold` 的大小关系。 我们维护一个长度为 的滑动窗口,每次计算窗口内的和 ,如果 大于等于 `threshold`,则答案加一。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 滑动窗口(状态滚动更新) 题型思路
题目描述
给你一个整数数组 arr 和两个整数 k 和 threshold 。
请你返回长度为 k 且平均值大于等于 threshold 的子数组数目。
示例 1:
输入:arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4 输出:3 解释:子数组 [2,5,5],[5,5,5] 和 [5,5,8] 的平均值分别为 4,5 和 6 。其他长度为 3 的子数组的平均值都小于 4 (threshold 的值)。
示例 2:
输入:arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5 输出:6 解释:前 6 个长度为 3 的子数组平均值都大于 5 。注意平均值不是整数。
提示:
1 <= arr.length <= 1051 <= arr[i] <= 1041 <= k <= arr.length0 <= threshold <= 104
解题思路
方法一:滑动窗口
不妨将 threshold 乘以 ,这样我们就可以直接比较窗口内的和与 threshold 的大小关系。
我们维护一个长度为 的滑动窗口,每次计算窗口内的和 ,如果 大于等于 threshold,则答案加一。
时间复杂度 ,其中 为数组 arr 的长度。空间复杂度 。
class Solution:
def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int:
threshold *= k
s = sum(arr[:k])
ans = int(s >= threshold)
for i in range(k, len(arr)):
s += arr[i] - arr[i - k]
ans += int(s >= threshold)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) because we process each element once while sliding the window. Space complexity is O(1) since we only need variables to track the current sum and the count of valid sub-arrays, regardless of input size. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can the candidate implement the sliding window approach efficiently?
- question_mark
Does the candidate handle edge cases such as when `k` equals the array length?
- question_mark
How well does the candidate explain their approach, especially with respect to avoiding recalculating sums repeatedly?
常见陷阱
外企场景- error
Incorrectly recalculating the sum for every sub-array from scratch instead of updating it incrementally.
- error
Missing edge cases like when the size of the sub-array `k` equals the array length.
- error
Not properly handling the condition where no sub-arrays meet the threshold, leading to returning an incorrect count.
进阶变体
外企场景- arrow_right_alt
How would this approach change if we need to track sub-arrays of variable sizes?
- arrow_right_alt
What if instead of an average, the threshold were a sum condition?
- arrow_right_alt
How could this solution be adapted for multidimensional arrays or matrices?