Skip to content

Commit 1358351

Browse files
committed
Add solution and test-cases for problem 3101
1 parent 7ce34f6 commit 1358351

File tree

3 files changed

+49
-22
lines changed

3 files changed

+49
-22
lines changed

leetcode/3101-3200/3101.Count-Alternating-Subarrays/README.md

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,36 @@
11
# [3101.Count Alternating Subarrays][title]
22

3-
> [!WARNING|style:flat]
4-
> This question is temporarily unanswered if you have good ideas. Welcome to [Create Pull Request PR](https://github.com/kylesliu/awesome-golang-algorithm)
5-
63
## Description
4+
You are given a binary array `nums`.
5+
6+
We call a subarray **alternating** if **no** two **adjacent** elements in the subarray have the **same** value.
7+
8+
Return the number of alternating subarrays in `nums`.
9+
710

811
**Example 1:**
912

1013
```
11-
Input: a = "11", b = "1"
12-
Output: "100"
13-
```
14+
Input: nums = [0,1,1,1]
1415
15-
## 题意
16-
> ...
16+
Output: 5
1717
18-
## 题解
18+
Explanation:
1919
20-
### 思路1
21-
> ...
22-
Count Alternating Subarrays
23-
```go
20+
The following subarrays are alternating: [0], [1], [1], [1], and [0,1].
2421
```
2522

23+
**Example 2:**
24+
25+
```
26+
Input: nums = [1,0,1,0]
27+
28+
Output: 10
29+
30+
Explanation:
31+
32+
Every subarray of the array is alternating. There are 10 possible subarrays that we can choose.
33+
```
2634

2735
## 结语
2836

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,25 @@
11
package Solution
22

3-
func Solution(x bool) bool {
4-
return x
3+
func Solution(nums []int) int64 {
4+
l, cnt := len(nums), 0
5+
ret := int64(l)
6+
start, end := 0, 1
7+
8+
for ; end < l; end++ {
9+
if nums[end] != nums[end-1] {
10+
continue
11+
}
12+
13+
length := end - start
14+
cnt = (length - 1) * length / 2
15+
ret += int64(cnt)
16+
17+
start = end
18+
}
19+
20+
length := end - start
21+
cnt = (length - 1) * length / 2
22+
ret += int64(cnt)
23+
24+
return ret
525
}

leetcode/3101-3200/3101.Count-Alternating-Subarrays/Solution_test.go

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,11 @@ func TestSolution(t *testing.T) {
1010
// 测试用例
1111
cases := []struct {
1212
name string
13-
inputs bool
14-
expect bool
13+
inputs []int
14+
expect int64
1515
}{
16-
{"TestCase", true, true},
17-
{"TestCase", true, true},
18-
{"TestCase", false, false},
16+
{"TestCase1", []int{0, 1, 1, 1}, 5},
17+
{"TestCase2", []int{1, 0, 1, 0}, 10},
1918
}
2019

2120
// 开始测试
@@ -30,10 +29,10 @@ func TestSolution(t *testing.T) {
3029
}
3130
}
3231

33-
// 压力测试
32+
// 压力测试
3433
func BenchmarkSolution(b *testing.B) {
3534
}
3635

37-
// 使用案列
36+
// 使用案列
3837
func ExampleSolution() {
3938
}

0 commit comments

Comments
 (0)