[LeetCode] 3101. Count Alternating Subarrays
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: nums = [0,1,1,1]
Output: 5
Explanation:
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.
Constraints:
1 <= nums.length <= 105
nums[i] is either 0 or 1.
交替子数组计数。
给你一个二进制数组nums 。如果一个子数组中 不存在 两个 相邻 元素的值 相同 的情况,我们称这样的子数组为 交替子数组 。
返回数组 nums 中交替子数组的数量。
思路
这道题不难。通过这道题我们可以学到如何计算交替数组的长度。这个思路有助于我们解决一些其他题目,详见相关题目
。
复杂度
时间O(n)
空间O(1)
代码
Java实现
class Solution {
public long countAlternatingSubarrays(int[] nums) {
int n = nums.length;
long res = 0;
long count = 0;
for (int i = 0; i < n; i++) {
if (i > 0 && nums[i] != nums[i - 1]) {
count++;
} else {
count = 1;
}
res += count;
}
return res;
}
}
相关题目
3101. Count Alternating Subarrays
3206. Alternating Groups I
3208. Alternating Groups II