Skip to content

Commit 322c541

Browse files
Create 3101. 交替子数组计数.md
1 parent e828d56 commit 322c541

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
#### 3101. 交替子数组计数
2+
3+
难度:中等
4+
5+
---
6+
7+
给你一个 二进制数组 `nums`
8+
9+
如果一个 子数组 中 **不存在** 两个 **相邻** 元素的值 **相同** 的情况,我们称这样的子数组为 **交替子数组**
10+
11+
返回数组 `nums` 中交替子数组的数量。
12+
13+
**示例 1:**
14+
15+
**输入:** nums = \[0,1,1,1\]
16+
17+
**输出:** 5
18+
19+
**解释:**
20+
21+
以下子数组是交替子数组:`[0]``[1]``[1]``[1]` 以及 `[0,1]`
22+
23+
**示例 2:**
24+
25+
**输入:** nums = \[1,0,1,0\]
26+
27+
**输出:** 10
28+
29+
**解释:**
30+
31+
数组的每个子数组都是交替子数组。可以统计在内的子数组共有 10 个。
32+
33+
**提示:**
34+
35+
* `1 <= nums.length <= 10^5`
36+
* `nums[i]` 不是 `0` 就是 `1`
37+
38+
---
39+
40+
双指针:找到数组里**每个最长交替数组**,每个最长数组的交替子数组的和为 $len * (len + 1) / 2$,将每个交替子数组的和求和即可。
41+
42+
```Go
43+
func countAlternatingSubarrays(nums []int) int64 {
44+
n := len(nums)
45+
res := int64(0)
46+
left, right := 0, 0
47+
for right < n {
48+
if right + 1 < n && nums[right] != nums[right + 1] {
49+
right++
50+
} else {
51+
res += calculate(right - left + 1)
52+
right = right + 1
53+
left = right
54+
}
55+
}
56+
return res
57+
}
58+
59+
func calculate(length int) int64 {
60+
return int64(length) * int64(length + 1) / 2
61+
}
62+
```

0 commit comments

Comments
 (0)