930. Binary Subarrays With Sum

Posted johnnyzhao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了930. Binary Subarrays With Sum相关的知识,希望对你有一定的参考价值。

package LeetCode_930

/**
 * 930. Binary Subarrays With Sum
 * https://leetcode.com/problems/binary-subarrays-with-sum/description/
 *
 * In an array A of 0s and 1s, how many non-empty subarrays have sum S?

Example 1:
Input: A = [1,0,1,0,1], S = 2
Output: 4
Explanation:
The 4 subarrays are bolded below:
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]
 * */
class Solution {
    //hashmap + prefixSum
    fun numSubarraysWithSum(A: IntArray, S: Int): Int {
        val map = HashMap<Int, Int>()
        //key:prefixSum value
        //value:number of appeared of the prefixSum value
        map.put(0, 1)
        var result = 0
        var prefixSum = 0
        for (num in A) {
            prefixSum += num
            result += map.getOrDefault(prefixSum - S, 0)
            map.put(prefixSum, 1 + map.getOrDefault(prefixSum, 0))
        }
        return result
    }
}

 

以上是关于930. Binary Subarrays With Sum的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode-930 Binary Subarrays With Sum(和相同的二元子数组)

108th LeetCode Weekly Contest Binary Subarrays With Sum

1031. Maximum Sum of Two Non-Overlapping Subarrays

689. Maximum Sum of 3 Non-Overlapping Subarrays

LeetCode 689. Maximum Sum of 3 Non-Overlapping Subarrays

[LeetCode] 1031. Maximum Sum of Two Non-Overlapping Subarrays