问题背景
给你一个整数数组 c o l o r s colors colors 它表示一个由红色和蓝色瓷砖组成的环,第 i i i块瓷砖的颜色为 c o l o r s [ i ] colors[i] colors[i]:
- c o l o r s [ i ] = = 0 colors[i] == 0 colors[i]==0 表示第 i i i 块瓷砖的颜色是 红色 。
- c o l o r s [ i ] = = 1 colors[i] == 1 colors[i]==1 表示第 i i i 块瓷砖的颜色是 蓝色 。
环中连续 3 3 3 块瓷砖的颜色如果是 交替 颜色(也就是说除了第一块和最后一块瓷砖以外,中间瓷砖的颜色与它 左边 和 右边 的颜色都不同),那么它被称为一个 交替 组。
请你返回 交替 组的数目。
注意 ,由于 c o l o r s colors colors 表示一个 环 ,第一块 瓷砖和 最后一块 瓷砖是相邻的。
数据约束
- 3 ≤ c o l o r s . l e n g t h ≤ 100 3 \le colors.length \le 100 3≤colors.length≤100
- 0 ≤ c o l o r s [ i ] ≤ 1 0 \le colors[i] \le 1 0≤colors[i]≤1
解题过程
这一题是要求 长度不小于给定值 的一种特例,参考那样的写法,只需要把其中的 k k k 改成 3 3 3 就可以通过。
除此之外,由于要求的长度好写判断,所以也可以避免按右端点累计,直接在每个位置上判断是否满足条件。但是时空复杂度都是一样的,这样写泛用性会更差。
需要注意的就是用模运算来映射,这一题标简单也有一部分用例简单的原因。
具体实现
按右端点统计
class Solution {public int numberOfAlternatingGroups(int[] colors) {int res = 0;int n = colors.length;int len = 0;for(int i = 0; i < 2 * n; i++) {if(i > 0 && colors[i % n] == colors[(i - 1) % n]) {len = 0;}len++;if(i >= n && len >= 3) {res++;}}return res;}
}
直接判断
class Solution {public int numberOfAlternatingGroups(int[] colors) {int res = 0;int n = colors.length;for(int i = 0; i < n; i++) {if(colors[i % n] != colors[(i - 1 + n) % n] && colors[(i - 1 + n) % n] == colors[(i + 1) % n]) {res++;}}return res;}
}