LeetCode 题解工作台

和相同的二元子数组

给你一个二元数组 nums ,和一个整数 goal ,请你统计并返回有多少个和为 goal 的 非空 子数组。 子数组 是数组的一段连续部分。 示例 1: 输入: nums = [1,0,1,0,1], goal = 2 输出: 4 解释: 有 4 个满足题目要求的子数组:[1,0,1]、[1,0,…

category

4

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

我们可以用数组或哈希表 记录每个前缀和出现的次数,其中 表示前缀和为 的子数组个数。初始时 $cnt[0] = 1$。 接下来我们遍历数组 `nums`,用变量 维护当前的前缀和,对于每个 ,我们可以计算出 $s - goal$ 出现的次数,即为以当前位置结尾的满足条件的子数组个数,累加到答案中。然后我们将 的计数值加 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个二元数组 nums ,和一个整数 goal ,请你统计并返回有多少个和为 goal 非空 子数组。

子数组 是数组的一段连续部分。

 

示例 1:

输入:nums = [1,0,1,0,1], goal = 2
输出:4
解释:
有 4 个满足题目要求的子数组:[1,0,1]、[1,0,1,0]、[0,1,0,1]、[1,0,1]

示例 2:

输入:nums = [0,0,0,0,0], goal = 0
输出:15

 

提示:

  • 1 <= nums.length <= 3 * 104
  • nums[i] 不是 0 就是 1
  • 0 <= goal <= nums.length
lightbulb

解题思路

方法一:数组或哈希表 + 前缀和

我们可以用数组或哈希表 cntcnt 记录每个前缀和出现的次数,其中 cnt[i]cnt[i] 表示前缀和为 ii 的子数组个数。初始时 cnt[0]=1cnt[0] = 1

接下来我们遍历数组 nums,用变量 ss 维护当前的前缀和,对于每个 ss,我们可以计算出 sgoals - goal 出现的次数,即为以当前位置结尾的满足条件的子数组个数,累加到答案中。然后我们将 ss 的计数值加 11

最终的答案即为满足条件的子数组个数。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为数组 nums 的长度。

1
2
3
4
5
6
7
8
9
10
class Solution:
    def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:
        cnt = Counter({0: 1})
        ans = s = 0
        for v in nums:
            s += v
            ans += cnt[s - goal]
            cnt[s] += 1
        return ans
speed

复杂度分析

指标
时间O(n)
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Checks if you can optimize counting subarrays without nested loops.

  • question_mark

    May ask why sliding window alone fails when zeros exist.

  • question_mark

    Looks for clear explanation of prefix sum mapping to goal counts.

warning

常见陷阱

外企场景
  • error

    Forgetting to initialize prefix sum count map with 0 sum seen once.

  • error

    Updating hash map before counting current subarrays can undercount.

  • error

    Misinterpreting zeros and ones leads to missing valid subarrays.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Count subarrays with sum less than or equal to goal.

  • arrow_right_alt

    Handle arrays with arbitrary integers, not just binary.

  • arrow_right_alt

    Return all subarrays instead of counting them.

help

常见问题

外企场景

和相同的二元子数组题解:数组·哈希·扫描 | LeetCode #930 中等