LeetCode 题解工作台

交替组 I

给你一个整数数组 colors ,它表示一个由红色和蓝色瓷砖组成的环,第 i 块瓷砖的颜色为 colors[i] : colors[i] == 0 表示第 i 块瓷砖的颜色是 红色 。 colors[i] == 1 表示第 i 块瓷砖的颜色是 蓝色 。 环中连续 3 块瓷砖的颜色如果是 交替 颜色(…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 滑动窗口(状态滚动更新)

bolt

答案摘要

我们令 $k = 3$,表示交替组的长度为 。 为了方便处理,我们可以将环展开成一个长度为 的数组,然后从左到右遍历这个数组,用一个变量 记录当前交替组的长度,如果遇到了相同的颜色,就将 重置为 ,否则将 加一。如果 $\textit{cnt} \ge k$,并且当前位置 大于等于 ,那么就找到了一个交替组,答案加一。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 滑动窗口(状态滚动更新) 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 colors ,它表示一个由红色和蓝色瓷砖组成的环,第 i 块瓷砖的颜色为 colors[i] :

  • colors[i] == 0 表示第 i 块瓷砖的颜色是 红色 。
  • colors[i] == 1 表示第 i 块瓷砖的颜色是 蓝色 。

环中连续 3 块瓷砖的颜色如果是 交替 颜色(也就是说中间瓷砖的颜色与它 左边 和 右边 的颜色都不同),那么它被称为一个 交替 组。

请你返回 交替 组的数目。

注意 ,由于 colors 表示一个  ,第一块 瓷砖和 最后一块 瓷砖是相邻的。

 

示例 1:

输入:colors = [1,1,1]

输出:0

解释:

示例 2:

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

输出:3

解释:

交替组包括:

 

提示:

  • 3 <= colors.length <= 100
  • 0 <= colors[i] <= 1
lightbulb

解题思路

方法一:一次遍历

我们令 k=3k = 3,表示交替组的长度为 33

为了方便处理,我们可以将环展开成一个长度为 2n2n 的数组,然后从左到右遍历这个数组,用一个变量 cnt\textit{cnt} 记录当前交替组的长度,如果遇到了相同的颜色,就将 cnt\textit{cnt} 重置为 11,否则将 cnt\textit{cnt} 加一。如果 cntk\textit{cnt} \ge k,并且当前位置 ii 大于等于 nn,那么就找到了一个交替组,答案加一。

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
    def numberOfAlternatingGroups(self, colors: List[int]) -> int:
        k = 3
        n = len(colors)
        ans = cnt = 0
        for i in range(n << 1):
            if i and colors[i % n] == colors[(i - 1) % n]:
                cnt = 1
            else:
                cnt += 1
            ans += i >= n and cnt >= k
        return ans
speed

复杂度分析

指标
时间complexity is O(n) since each tile is checked once in a sliding window. Space complexity is O(1) as only counters and indices are maintained without extra arrays.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Can you apply a sliding window instead of nested loops?

  • question_mark

    How do you handle the circular nature of the array?

  • question_mark

    Are you updating counts efficiently without redundant recalculations?

warning

常见陷阱

外企场景
  • error

    Forgetting the circular wrap-around, causing missed groups at array ends.

  • error

    Incorrectly comparing tiles without considering the middle tile distinction.

  • error

    Recomputing full windows instead of using running updates, increasing time complexity.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Count alternating groups of size 4 instead of 3 in a circular array.

  • arrow_right_alt

    Use more than two colors and identify alternating patterns.

  • arrow_right_alt

    Return indices of all alternating groups instead of just the count.

help

常见问题

外企场景

交替组 I题解:滑动窗口(状态滚动更新) | LeetCode #3206 简单