码迷,mamicode.com
首页 > 其他好文 > 详细

930. Binary Subarrays With Sum

时间:2020-04-25 20:51:26      阅读:54      评论:0      收藏:0      [点我收藏+]

标签:result   tps   problem   script   out   http   problems   for   color   

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

标签:result   tps   problem   script   out   http   problems   for   color   

原文地址:https://www.cnblogs.com/johnnyzhao/p/12775114.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!