diff --git a/leetcode/3101-3200/3101.Count-Alternating-Subarrays/README.md b/leetcode/3101-3200/3101.Count-Alternating-Subarrays/README.md index 36c8740aa..456cafd63 100755 --- a/leetcode/3101-3200/3101.Count-Alternating-Subarrays/README.md +++ b/leetcode/3101-3200/3101.Count-Alternating-Subarrays/README.md @@ -1,28 +1,36 @@ # [3101.Count Alternating Subarrays][title] -> [!WARNING|style:flat] -> This question is temporarily unanswered if you have good ideas. Welcome to [Create Pull Request PR](https://github.com/kylesliu/awesome-golang-algorithm) - ## Description +You are given a binary array `nums`. + +We call a subarray **alternating** if **no** two **adjacent** elements in the subarray have the **same** value. + +Return the number of alternating subarrays in `nums`. + **Example 1:** ``` -Input: a = "11", b = "1" -Output: "100" -``` +Input: nums = [0,1,1,1] -## 题意 -> ... +Output: 5 -## 题解 +Explanation: -### 思路1 -> ... -Count Alternating Subarrays -```go +The following subarrays are alternating: [0], [1], [1], [1], and [0,1]. ``` +**Example 2:** + +``` +Input: nums = [1,0,1,0] + +Output: 10 + +Explanation: + +Every subarray of the array is alternating. There are 10 possible subarrays that we can choose. +``` ## 结语 diff --git a/leetcode/3101-3200/3101.Count-Alternating-Subarrays/Solution.go b/leetcode/3101-3200/3101.Count-Alternating-Subarrays/Solution.go index d115ccf5e..a3eac3ab1 100644 --- a/leetcode/3101-3200/3101.Count-Alternating-Subarrays/Solution.go +++ b/leetcode/3101-3200/3101.Count-Alternating-Subarrays/Solution.go @@ -1,5 +1,25 @@ package Solution -func Solution(x bool) bool { - return x +func Solution(nums []int) int64 { + l, cnt := len(nums), 0 + ret := int64(l) + start, end := 0, 1 + + for ; end < l; end++ { + if nums[end] != nums[end-1] { + continue + } + + length := end - start + cnt = (length - 1) * length / 2 + ret += int64(cnt) + + start = end + } + + length := end - start + cnt = (length - 1) * length / 2 + ret += int64(cnt) + + return ret } diff --git a/leetcode/3101-3200/3101.Count-Alternating-Subarrays/Solution_test.go b/leetcode/3101-3200/3101.Count-Alternating-Subarrays/Solution_test.go index 14ff50eb4..bf4a919de 100644 --- a/leetcode/3101-3200/3101.Count-Alternating-Subarrays/Solution_test.go +++ b/leetcode/3101-3200/3101.Count-Alternating-Subarrays/Solution_test.go @@ -10,12 +10,11 @@ func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string - inputs bool - expect bool + inputs []int + expect int64 }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", []int{0, 1, 1, 1}, 5}, + {"TestCase2", []int{1, 0, 1, 0}, 10}, } // 开始测试 @@ -30,10 +29,10 @@ func TestSolution(t *testing.T) { } } -// 压力测试 +// 压力测试 func BenchmarkSolution(b *testing.B) { } -// 使用案列 +// 使用案列 func ExampleSolution() { }