[LeetCode] 3206. Alternating Groups I

There is a circle of red and blue tiles. You are given an array of integers colors. The color of tile i is represented by colors[i]:
colors[i] == 0 means that tile i is red.
colors[i] == 1 means that tile i is blue.
Every 3 contiguous tiles in the circle with alternating colors (the middle tile has a different color from its left and right tiles) is called an alternating group.

Return the number of alternating groups.

Note that since colors represents a circle, the first and the last tiles are considered to be next to each other.

Example 1:
Input: colors = [1,1,1]
Output: 0
Explanation:
Example 1

Example 2:
Input: colors = [0,1,0,0,1]
Output: 3
Explanation:
Example 2

Alternating groups:
Example 2
Example 2
Example 2

Constraints:
3 <= colors.length <= 100
0 <= colors[i] <= 1

交替组 I。

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

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

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

请你返回 交替 组的数目。

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

思路

这个题目其实是让你看一个长度为 3 的窗口里面元素的情况。不过这道题我们只需要考虑窗口内的 3 个元素是否是交替的即可。记得遍历到最后的时候下标要取模。

复杂度

时间O(n)
空间O(1)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
int n;

public int numberOfAlternatingGroups(int[] colors) {
n = colors.length;
int res = 0;
for (int i = 0; i < n; i++) {
if (helper(colors, i)) {
res++;
}
}
return res;
}

private boolean helper(int[] colors, int index) {
int first = colors[index % n];
int second = colors[(index + 1) % n];
int third = colors[(index + 2) % n];
if (first != second && second != third) {
return true;
}
return false;
}
}

[LeetCode] 3206. Alternating Groups I
https://shurui91.github.io/posts/2490180647.html
Author
Aaron Liu
Posted on
November 25, 2024
Licensed under