[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实现

class Solution {
	int n;

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

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

相关题目

3101. Count Alternating Subarrays
3206. Alternating Groups I
3208. Alternating Groups II
posted @ 2024-11-26 04:09  CNoodle  阅读(56)  评论(0)    收藏  举报