Location>code7788 >text

2024-11-20: Counting alternating subarrays. In go, given a binary array nums, we call a subarray an alternating subarray if none of its neighboring elements have the same value. Return the total number of alternating subarrays in the array nums. The outpu

Popularity:914 ℃/2024-11-20 13:35:14

2024-11-20: Alternate subarray counting. In go, given a binary array nums.

We call a subarray an alternating subarray if none of its neighboring elements have the same value.

Please return the total number of alternating subarrays in the array nums.

Input: nums = [0,1,1,1].

Output: 5.

Explanation:

The following subarrays are alternating subarrays: [0], [1], [1], [1], and [0,1].

Answer 2024-11-20:

chatgpt

Title from leetcode3101.

The broad steps are as follows:

1.input data: First, we have an array of binary arraysnumsFor examplenums = [0, 1, 1, 1]. Our goal is to count the number of all alternating subarrays in this array.

2.Definition of alternating subarrays: An alternating subarray is a subarray in which neighboring elements must have different values. Example:

2.1. arrays[0] cap (a poem)[1] are all alternating subarrays because their elements are not duplicated adjacent to each other.

2.2. Arrays[1, 1] is not an alternating subarray, since two neighboring elements are 1.

3.Initializing Variables

3.1.res: Used to store the total number of alternating subarrays, initial value is 0.

3.2.cur: Used to record the length of the current alternating subarray, the initial value is 0.

3.3.pre: An auxiliary variable that holds the value of the previous element, initially set to -1 (to facilitate comparison with the first element).

4.Iterate over the array

4.1. for a given arraynums Each element in thea, perform the following operations:

4.1.1.Non-duplication: If the current elementa Same as the previous elementpre is not equal, indicating that the alternating state continues, so the current count ofcur Plus 1.

4.1.2.duplication: If the current elementa Same as the previous elementpre are equal, then the alternate state is destroyed, and the current count ofcur Reset to 1 for the current elementa as the starting element of a new alternating subarray.

4.1.3.pre for the current elementafor comparison in the next iteration.

4.1.4. Place the currentcur Values are added to the totalres in. This will ensure that it contains all alternating subarrays with the current element as the ending element.

5.End traversal: When traversing the entire array, theres will contain the total number of all possible alternating subarrays.

6.Return results: Finally, the function returnsres, which is the number of alternating subarrays we need.

Illustrative analysis

take an inputnums = [0, 1, 1, 1] As an example:

  • Processing the first element0cur Increase to 1.res to 1 (subarray)[0])。

  • Handling the second element1cur Increase to 2.res to 3 (including subarrays)[1] cap (a poem)[0, 1])。

  • Processing the next two elements1

    • For the first repetition1, due to the fact that with the previouspre(also1) are equal.cur reset to 1.res Increase to 4 (subarray)[1])。

    • For the second repetition1Likewise.cur reset to 1.res Increase to 5 (plus[1])。

  • Thus, the final output is 5 and contains the alternating subarray of[0][1][1][1][0, 1]

Time complexity and space complexity

  • time complexity: O(n), where n is the arraynums The length of the array is proportional to the length of the array. Since the calculation is performed by traversing the array only once, the number of operations required is proportional to the length of the array.

  • (math.) space complexity: O(1), because the variables used (rescurpre) are constant spaces that do not depend on the size of the input array and are not stored using additional data structures.

The full Go code is below:

package main

import (
	"fmt"
)

func countAlternatingSubarrays(nums []int) int64 {
	var res, cur int64
	pre := -1
	for _, a := range nums {
		if pre != a {
			cur++
		} else {
			cur = 1
		}
		pre = a
		res += cur
	}
	return res
}

func main() {
	nums := []int{0, 1, 1, 1}
	(countAlternatingSubarrays(nums))
}

在这里插入图片描述

The full Rust code is below:

fn count_alternating_subarrays(nums: Vec<i32>) -> i64 {
    let mut res = 0;
    let mut cur = 0; let mut pre = -1; // for
    let mut pre = -1; // for recording the previous value

    for &a in &nums {
        if pre ! = a { if pre !
            cur += 1; // if different, add 1 to the length of the current alternate subarray
        } else {
            cur = 1; // if equal, reset to 1
        }
        pre = a; res += cur; // Add alternates.
        res += cur; // add the number of alternating subarrays
    }

    res // return the result
}

fn main() {
    println!("{}", count_alternating_subarrays(nums)); count_alternating_subarrays(nums); println!
    println!("{}", count_alternating_subarrays(nums));
}

在这里插入图片描述