【每日一题】3206. 交替组
给你一个整数数组 colors
,它表示一个由红色和蓝色瓷砖组成的环,第 i
块瓷砖的颜色为 colors[i]
:
colors[i] == 0
表示第i
块瓷砖的颜色是 红色 。colors[i] == 1
表示第i
块瓷砖的颜色是 蓝色 。
环中连续 3 块瓷砖的颜色如果是 交替 颜色(也就是说中间瓷砖的颜色与它 左边 和 右边 的颜色都不同),那么它被称为一个 交替 组。
请你返回 交替 组的数目。
注意 ,由于 colors
表示一个 环 ,第一块 瓷砖和 最后一块 瓷砖是相邻的。
class Solution: def numberOfAlternatingGroups(self, colors: List[int]) -> int: k = 3 n = len(colors) ans = cnt = 0 for i in range(n * 2): # 环形数组的处理方法 # cnt表示以i结尾交替组的长度 if i > 0 and colors[i % n] == colors[(i - 1) % n]: cnt = 0 cnt += 1 if i >= n and cnt >= k: ans += 1 return ans