LeetCode 题解工作台

交替子数组计数

给你一个 二进制数组 nums 。 如果一个 子数组 中 不存在 两个 相邻 元素的值 相同 的情况,我们称这样的子数组为 交替子数组 。 返回数组 nums 中交替子数组的数量。 示例 1: 输入: nums = [0,1,1,1] 输出: 5 解释: 以下子数组是交替子数组: [0] 、 [1]…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·数学

bolt

答案摘要

我们可以枚举以每个位置结尾的子数组,计算满足条件的子数组的数量,累加所有位置的满足条件的子数组的数量即可。 具体地,我们定义变量 表示以元素 结尾的满足条件的子数组的数量,初始时我们将 置为 ,表示以第一个元素结尾的满足条件的子数组的数量为 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个二进制数组 nums

如果一个子数组不存在 两个 相邻 元素的值 相同 的情况,我们称这样的子数组为 交替子数组

返回数组 nums 中交替子数组的数量。

 

示例 1:

输入: nums = [0,1,1,1]

输出: 5

解释:

以下子数组是交替子数组:[0][1][1][1] 以及 [0,1]

示例 2:

输入: nums = [1,0,1,0]

输出: 10

解释:

数组的每个子数组都是交替子数组。可以统计在内的子数组共有 10 个。

 

提示:

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

解题思路

方法一:枚举

我们可以枚举以每个位置结尾的子数组,计算满足条件的子数组的数量,累加所有位置的满足条件的子数组的数量即可。

具体地,我们定义变量 ss 表示以元素 nums[i]nums[i] 结尾的满足条件的子数组的数量,初始时我们将 ss 置为 11,表示以第一个元素结尾的满足条件的子数组的数量为 11

接下来,我们从第二个元素开始遍历数组,对于每个位置 ii,我们根据 nums[i]nums[i]nums[i1]nums[i-1] 的关系更新 ss 的值:

  • 如果 nums[i]nums[i1]nums[i] \neq nums[i-1],则 ss 的值增加 11,即 s=s+1s = s + 1
  • 如果 nums[i]=nums[i1]nums[i] = nums[i-1],则 ss 的值重置为 11,即 s=1s = 1

然后,我们将 ss 的值累加到答案中,继续遍历数组的下一个位置,直到遍历完整个数组。

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

1
2
3
4
5
6
7
8
class Solution:
    def countAlternatingSubarrays(self, nums: List[int]) -> int:
        ans = s = 1
        for a, b in pairwise(nums):
            s = s + 1 if a != b else 1
            ans += s
        return ans
speed

复杂度分析

指标
时间complexity is O(n) for a single traversal or DP solution, where n is nums.length. Space complexity is O(n) for DP or O(1) for linear counting with a rolling variable.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Ask for a solution that handles large arrays efficiently.

  • question_mark

    Check if the candidate recognizes overlapping subarrays and can optimize counting.

  • question_mark

    Probe understanding of array patterns and use of cumulative math formulas.

warning

常见陷阱

外企场景
  • error

    Counting only subarrays of length 2 and missing longer alternating sequences.

  • error

    Resetting counts incorrectly when consecutive elements are equal, undercounting subarrays.

  • error

    Using nested loops, leading to timeouts for arrays near length 10^5.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Count alternating subarrays in ternary arrays instead of binary arrays.

  • arrow_right_alt

    Return the length of the longest alternating subarray instead of total count.

  • arrow_right_alt

    Count alternating subarrays that start with 1 only, skipping those starting with 0.

help

常见问题

外企场景

交替子数组计数题解:数组·数学 | LeetCode #3101 中等