Leetcode: Subarray Sum Equals K\\\Binary Subarrays With Sum

Problem

Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

Example 1:
Input: nums = [1,1,1], k = 2
Output: 2
Note:
The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

Solution

我们用一个HashMap<preSum,count>来保存:和为preSum的subarray的数量。
通过遍历整个输入的nums数组,不断更新HashMap。
在遍历到时间 t t t 时, n u m s [ 0 ] + n u m s [ 1 ] + . . . + n u m s [ t − 1 ] = p r e S u m nums[0]+nums[1]+...+nums[t-1] = preSum nums[0]+nums[1]+...+nums[t1]=preSum,在这个时刻之前共有 H a s h M a p [ V ] HashMap[V] HashMap[V]( V = p r e s u m − k V = presum-k V=presumk)个indices j j j 使得 n u m s [ 0 ] + n u m s [ 1 ] + . . . + n u m s [ j ] = V nums[0]+nums[1]+...+nums[j] = V nums[0]+nums[1]+...+nums[j]=V,且 n u m s [ j ] + . . . + n u m s [ t − 1 ] = p r e S u m − V nums[j]+...+nums[t-1] =preSum- V nums[j]+...+nums[t1]=preSumV
所以在每个时刻我们都将 H a s h M a p [ p r e S u m − k ] HashMap[preSum-k] HashMap[preSumk]累加到我们的结果中。

class Solution:
    def subarraySum(self, nums: 'List[int]', k: 'int') -> 'int':
        res = 0
        hashmap = {0:1}
        presum = 0
        for n in nums:
            presum = n+presum
            key = presum-k
            if key in hashmap.keys():
                res += hashmap[key]
            hashmap[presum] = hashmap.get(presum,0)+1
        return res

另一道题解法和本题相同:

Problem

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]

Note:

A.length <= 30000
0 <= S <= A.length
A[i] is either 0 or 1.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值