Skip to content

Commit de294fa

Browse files
committed
3206.交替组 I
1 parent 468713e commit de294fa

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package leetcode_3206_alternating_groups_i
2+
3+
// 3206. 交替组 I
4+
// https://leetcode.cn/problems/alternating-groups-i
5+
6+
// numberOfAlternatingGroups 顺序遍历
7+
// 时间复杂度: O(n)
8+
// 空间复杂度: O(1)
9+
func numberOfAlternatingGroups(colors []int) int {
10+
var ans int
11+
n := len(colors)
12+
if n <= 2 {
13+
return ans
14+
}
15+
for i := 0; i < n; i++ {
16+
need := (colors[i] + 1) % 2
17+
before := i - 1
18+
after := i + 1
19+
if before < 0 {
20+
before = n - 1
21+
}
22+
if after > n-1 {
23+
after = 0
24+
}
25+
if colors[before] == need && colors[after] == need {
26+
ans++
27+
}
28+
}
29+
return ans
30+
}

0 commit comments

Comments
 (0)