-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy path3206.alternating-groups-i.cpp
More file actions
59 lines (56 loc) · 1.38 KB
/
3206.alternating-groups-i.cpp
File metadata and controls
59 lines (56 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Tag: Array, Sliding Window
// Time: O(N)
// Space: O(1)
// Ref: -
// Note: -
// There is a circle of red and blue tiles. You are given an array of integers colors. The color of tile i is represented by colors[i]:
//
// colors[i] == 0 means that tile i is red.
// colors[i] == 1 means that tile i is blue.
//
// Every 3 contiguous tiles in the circle with alternating colors (the middle tile has a different color from its left and right tiles) is called an alternating group.
// 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:
//
// Input: colors = [1,1,1]
// Output: 0
// Explanation:
//
//
// Example 2:
//
// Input: colors = [0,1,0,0,1]
// Output: 3
// Explanation:
//
// Alternating groups:
//
//
//
// Constraints:
//
// 3 <= colors.length <= 100
// 0 <= colors[i] <= 1
//
//
class Solution {
public:
int numberOfAlternatingGroups(vector<int>& colors) {
int n = colors.size();
int k = 3;
int i = 0;
int res = 0;
for (int j = 1; i < n; j++) {
if (colors[j % n] == colors[(j - 1) % n]) {
i = j;
}
if (j - i + 1 == k) {
res += 1;
i += 1;
}
}
return res;
}
};