LeetCode 题解工作台
将数组划分成若干好子数组的方式
给你一个二元数组 nums 。 如果数组中的某个子数组 恰好 只存在 一 个值为 1 的元素,则认为该子数组是一个 好子数组 。 请你统计将数组 nums 划分成若干 好子数组 的方法数,并以整数形式返回。由于数字可能很大,返回其对 10 9 + 7 取余 之后的结果。 子数组是数组中的一个连续 非…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
根据题目描述,我们可以在两个 之间画一条分割线,假设两个 之间的下标分别为 和 ,那么可以画的不同分割线的数量为 $i - j$。我们找出所有满足条件的 和 ,然后将所有的 $i - j$ 相乘即可。如果找不到两个 之间的分割线,那么说明数组中不存在 ,此时答案为 。 时间复杂度 ,其中 为数组长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个二元数组 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 <= 1050 <= nums[i] <= 1
解题思路
方法一:乘法原理
根据题目描述,我们可以在两个 之间画一条分割线,假设两个 之间的下标分别为 和 ,那么可以画的不同分割线的数量为 。我们找出所有满足条件的 和 ,然后将所有的 相乘即可。如果找不到两个 之间的分割线,那么说明数组中不存在 ,此时答案为 。
时间复杂度 ,其中 为数组长度。空间复杂度 。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | 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 |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.