和相同的二元子数组

描述 在由若干 0 和 1 组成的数组 A 中,有多少个和为 S 的非空子数组。 A.length <= 30000 0 <= S <= A.length A[i] 为 0 或 1

解题步骤

  1. 初始化变量

    • res 记录符合条件的子数组数量。

    • psum 累加当前数组元素的前缀和。

    • c 使用 defaultdict(int) 来记录每个前缀和出现的次数,并初始化 c[0] = 1

  2. from typing import (
        List,
    )
    from collections import defaultdict
    
    class Solution:
        """
        @param a: an array
        @param s: the sum
        @return: the number of non-empty subarrays
        """
        def num_subarrays_with_sum(self, a: List[int], s: int) -> int:
            # Write your code here.
            #双指针的追逐指针
            res = 0
            psum = 0
            c = defaultdict(int)
            c[0] = 1 #重点
            for i in a:
                psum += i
                res += c[psum - s]
                c[psum] += 1
            return res
            
                    
    
    
    
    

Last updated