3208. Alternating Groups II
-
Extend the Array: To handle the circular nature of the array, extend the
colors
array by appending the firstk-1
elements to its end. This allows us to easily check for alternating groups that wrap around the end of the array. -
Initialize Counters:
res
to store the number of alternating groups.cnt
to count the length of the current alternating group.
-
Iterate Through the Extended Array:
- For each tile, check if its color is different from the previous tile.
- If it is, increment the
cnt
counter. - If it isn't, reset the
cnt
counter to 1. - If the
cnt
counter reachesk
, increment theres
counter as it indicates the end of an alternating group.
-
Return the Result: Finally, return the
res
counter, which represents the number of alternating groups of lengthk
.
class Solution {
public:
int numberOfAlternatingGroups(vector<int>& colors, int k)
{
for (int i = 0; i < k - 1; ++i)
{
colors.push_back(colors[i]);
}
int res = 0;
// cnt 用來記錄長度是否達到 k
int cnt = 1;
for (int i = 1; i < colors.size(); ++i)
{
// 如果是交錯的格子,則 cnt++
if (colors[i] != colors[i - 1])
{
++cnt;
}
else
{
// 如果不是交錯的格子,則 reset cnt= 1
cnt = 1;
}
// 如果 cnt 達到 k,則結果 + 1
if (cnt >= k) ++res;
}
return res;
}
};
- T:
- S: