LeetCode 题解工作台

将数组划分成若干好子数组的方式

给你一个二元数组 nums 。 如果数组中的某个子数组 恰好 只存在 一 个值为 1 的元素,则认为该子数组是一个 好子数组 。 请你统计将数组 nums 划分成若干 好子数组 的方法数,并以整数形式返回。由于数字可能很大,返回其对 10 9 + 7 取余 之后的结果。 子数组是数组中的一个连续 非…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

bolt

答案摘要

根据题目描述,我们可以在两个 之间画一条分割线,假设两个 之间的下标分别为 和 ,那么可以画的不同分割线的数量为 $i - j$。我们找出所有满足条件的 和 ,然后将所有的 $i - j$ 相乘即可。如果找不到两个 之间的分割线,那么说明数组中不存在 ,此时答案为 。 时间复杂度 ,其中 为数组长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个二元数组 nums

如果数组中的某个子数组 恰好 只存在 个值为 1 的元素,则认为该子数组是一个 好子数组

请你统计将数组 nums 划分成若干 好子数组 的方法数,并以整数形式返回。由于数字可能很大,返回其对 109 + 7 取余 之后的结果。

子数组是数组中的一个连续 非空 元素序列。

 

示例 1:

输入:nums = [0,1,0,0,1]
输出:3
解释:存在 3 种可以将 nums 划分成若干好子数组的方式:
- [0,1] [0,0,1]
- [0,1,0] [0,1]
- [0,1,0,0] [1]

示例 2:

输入:nums = [0,1,0]
输出:1
解释:存在 1 种可以将 nums 划分成若干好子数组的方式:
- [0,1,0]

 

提示:

  • 1 <= nums.length <= 105
  • 0 <= nums[i] <= 1
lightbulb

解题思路

方法一:乘法原理

根据题目描述,我们可以在两个 11 之间画一条分割线,假设两个 11 之间的下标分别为 jjii,那么可以画的不同分割线的数量为 iji - j。我们找出所有满足条件的 jjii,然后将所有的 iji - j 相乘即可。如果找不到两个 11 之间的分割线,那么说明数组中不存在 11,此时答案为 00

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

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
    def numberOfGoodSubarraySplits(self, nums: List[int]) -> int:
        mod = 10**9 + 7
        ans, j = 1, -1
        for i, x in enumerate(nums):
            if x == 0:
                continue
            if j > -1:
                ans = ans * (i - j) % mod
            j = i
        return 0 if j == -1 else ans
speed

复杂度分析

指标
时间complexity is O(n) for a single pass to identify 1 positions and compute dp transitions. Space complexity is O(k) where k is the number of 1s, as we only store dp states and positions of 1s.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Check for edge case when the array contains only zeros; answer should be 0.

  • question_mark

    Ask about handling large arrays and modulo operations to prevent integer overflow.

  • question_mark

    Probe understanding of state transition DP and distances between consecutive 1s.

warning

常见陷阱

外企场景
  • error

    Forgetting to return 0 when there are no 1s in the array.

  • error

    Incorrectly handling zeros at the beginning or end of the array in the DP calculation.

  • error

    Neglecting the modulo operation, which can cause integer overflow for large arrays.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Allow subarrays to contain at most one 1 instead of exactly one 1, changing the DP transition rules.

  • arrow_right_alt

    Count splits where each good subarray contains exactly k ones, requiring generalized state transitions.

  • arrow_right_alt

    Consider arrays with more than two distinct values, extending the definition of good subarrays.

help

常见问题

外企场景

将数组划分成若干好子数组的方式题解:状态·转移·动态规划 | LeetCode #2750 中等