comments | difficulty | edit_url | rating | source | tags | ||
---|---|---|---|---|---|---|---|
true |
Medium |
1721 |
Biweekly Contest 134 Q3 |
|
There is a circle of red and blue tiles. You are given an array of integers colors
and an integer k
. The color of tile i
is represented by colors[i]
:
colors[i] == 0
means that tilei
is red.colors[i] == 1
means that tilei
is blue.
An alternating group is every k
contiguous tiles in the circle with alternating colors (each tile in the group except the first and last one has a different color from its left and right tiles).
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:
Example 2:
Example 3:
Constraints:
3 <= colors.length <= 105
0 <= colors[i] <= 1
3 <= k <= colors.length
We can unfold the ring into an array of length
After the traversal, we return the answer.
The time complexity is
class Solution:
def numberOfAlternatingGroups(self, colors: List[int], k: int) -> int:
n = len(colors)
ans = cnt = 0
for i in range(n << 1):
if i and colors[i % n] == colors[(i - 1) % n]:
cnt = 1
else:
cnt += 1
ans += i >= n and cnt >= k
return ans
class Solution {
public int numberOfAlternatingGroups(int[] colors, int k) {
int n = colors.length;
int ans = 0, cnt = 0;
for (int i = 0; i < n << 1; ++i) {
if (i > 0 && colors[i % n] == colors[(i - 1) % n]) {
cnt = 1;
} else {
++cnt;
}
ans += i >= n && cnt >= k ? 1 : 0;
}
return ans;
}
}
class Solution {
public:
int numberOfAlternatingGroups(vector<int>& colors, int k) {
int n = colors.size();
int ans = 0, cnt = 0;
for (int i = 0; i < n << 1; ++i) {
if (i && colors[i % n] == colors[(i - 1) % n]) {
cnt = 1;
} else {
++cnt;
}
ans += i >= n && cnt >= k ? 1 : 0;
}
return ans;
}
};
func numberOfAlternatingGroups(colors []int, k int) (ans int) {
n := len(colors)
cnt := 0
for i := 0; i < n<<1; i++ {
if i > 0 && colors[i%n] == colors[(i-1)%n] {
cnt = 1
} else {
cnt++
}
if i >= n && cnt >= k {
ans++
}
}
return
}
function numberOfAlternatingGroups(colors: number[], k: number): number {
const n = colors.length;
let [ans, cnt] = [0, 0];
for (let i = 0; i < n << 1; ++i) {
if (i && colors[i % n] === colors[(i - 1) % n]) {
cnt = 1;
} else {
++cnt;
}
ans += i >= n && cnt >= k ? 1 : 0;
}
return ans;
}