欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > 【Leetcode 每日一题】3206. 交替组 I

【Leetcode 每日一题】3206. 交替组 I

2025/7/3 17:42:51 来源:https://blog.csdn.net/2401_88859777/article/details/144049268  浏览:    关键词:【Leetcode 每日一题】3206. 交替组 I

问题背景

给你一个整数数组 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 3colors.length100
  • 0 ≤ c o l o r s [ i ] ≤ 1 0 \le colors[i] \le 1 0colors[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;}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词