Every day a Leetcode
题目来源:3206. 交替组 I
解法1:模拟
向数组 colors 后面插入 colors[0] 和 colors[1],模拟成一个环的效果。
代码:
/*
* @lc app=leetcode.cn id=3206 lang=cpp
*
* [3206] 交替组 I
*/
// @lc code=start
class Solution
{
public:
int numberOfAlternatingGroups(vector<int> &colors)
{
int n = colors.size();
colors.push_back(colors[0]);
colors.push_back(colors[1]);
int cnt = 0;
for (int i = 0; i < n; i++)
{
if (colors[i] != colors[i + 1] && colors[i + 1] != colors[i + 2])
cnt++;
}
return cnt;
}
};
// @lc code=end
结果:
复杂度分析:
时间复杂度:O(n),其中 n 是数组 colors 的长度。
空间复杂度:O(1)。