LeetCode 题解工作台
全 0 子数组的数目
给你一个整数数组 nums ,返回全部为 0 的 子数组 数目。 子数组 是一个数组中一段连续非空元素组成的序列。 示例 1: 输入: nums = [1,3,0,0,2,0,0,4] 输出: 6 解释: 子数组 [0] 出现了 4 次。 子数组 [0,0] 出现了 2 次。 不存在长度大于 2 的…
2
题型
6
代码语言
3
相关题
当前训练重点
中等 · 数组·数学
答案摘要
我们遍历数组 ,用变量 记录当前连续的 的个数。那么对于当前遍历到的元素 ,如果 为 ,则 自增 ,以当前 为结尾的全 子数组的个数为 ,将其累加到答案中。否则,我们将 置为 。 遍历结束后,返回答案即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个整数数组 nums ,返回全部为 0 的 子数组 数目。
子数组 是一个数组中一段连续非空元素组成的序列。
示例 1:
输入:nums = [1,3,0,0,2,0,0,4] 输出:6 解释: 子数组 [0] 出现了 4 次。 子数组 [0,0] 出现了 2 次。 不存在长度大于 2 的全 0 子数组,所以我们返回 6 。
示例 2:
输入:nums = [0,0,0,2,0,0] 输出:9 解释: 子数组 [0] 出现了 5 次。 子数组 [0,0] 出现了 3 次。 子数组 [0,0,0] 出现了 1 次。 不存在长度大于 3 的全 0 子数组,所以我们返回 9 。
示例 3:
输入:nums = [2,10,2019] 输出:0 解释:没有全 0 子数组,所以我们返回 0 。
提示:
1 <= nums.length <= 105-109 <= nums[i] <= 109
解题思路
方法一:遍历计数
我们遍历数组 ,用变量 记录当前连续的 的个数。那么对于当前遍历到的元素 ,如果 为 ,则 自增 ,以当前 为结尾的全 子数组的个数为 ,将其累加到答案中。否则,我们将 置为 。
遍历结束后,返回答案即可。
时间复杂度 ,其中 是数组 的长度。空间复杂度 。
相似题目:
class Solution:
def zeroFilledSubarray(self, nums: List[int]) -> int:
ans = cnt = 0
for x in nums:
if x == 0:
cnt += 1
ans += cnt
else:
cnt = 0
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate recognizes the need to count consecutive zeros efficiently.
- question_mark
The candidate can optimize space usage while keeping the time complexity linear.
- question_mark
The candidate avoids brute force and handles large input sizes effectively.
常见陷阱
外企场景- error
Forgetting to reset the consecutive zero count after encountering a non-zero element.
- error
Underestimating the total number of subarrays when multiple consecutive zeros appear.
- error
Using nested loops to check for zero subarrays, leading to inefficient solutions.
进阶变体
外企场景- arrow_right_alt
Modify the problem to count subarrays filled with ones instead of zeros.
- arrow_right_alt
Consider a similar problem but with non-zero elements where you count subarrays with sums equal to a target value.
- arrow_right_alt
Extend the problem to multidimensional arrays, counting subarrays in a 2D matrix.