LeetCode 题解工作台

全 0 子数组的数目

给你一个整数数组 nums ,返回全部为 0 的 子数组 数目。 子数组 是一个数组中一段连续非空元素组成的序列。 示例 1: 输入: nums = [1,3,0,0,2,0,0,4] 输出: 6 解释: 子数组 [0] 出现了 4 次。 子数组 [0,0] 出现了 2 次。 不存在长度大于 2 的…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·数学

bolt

答案摘要

我们遍历数组 ,用变量 记录当前连续的 的个数。那么对于当前遍历到的元素 ,如果 为 ,则 自增 ,以当前 为结尾的全 子数组的个数为 ,将其累加到答案中。否则,我们将 置为 。 遍历结束后,返回答案即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 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
lightbulb

解题思路

方法一:遍历计数

我们遍历数组 nums\textit{nums},用变量 cnt\textit{cnt} 记录当前连续的 00 的个数。那么对于当前遍历到的元素 xx,如果 xx00,则 cnt\textit{cnt} 自增 11,以当前 xx 为结尾的全 00 子数组的个数为 cnt\textit{cnt},将其累加到答案中。否则,我们将 cnt\textit{cnt} 置为 00

遍历结束后,返回答案即可。

时间复杂度 O(n)O(n),其中 nn 是数组 nums\textit{nums} 的长度。空间复杂度 O(1)O(1)

相似题目:

1
2
3
4
5
6
7
8
9
10
11
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

全 0 子数组的数目题解:数组·数学 | LeetCode #2348 中等