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

本文介绍了一种高效算法,用于计算一个整数数组中所有连续子数组的总数,这些子数组的和等于给定整数K。通过使用HashMap记录前缀和的出现次数,可以在O(n)的时间复杂度内解决该问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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。
在遍历到时间 ttt 时,nums[0]+nums[1]+...+nums[t−1]=preSumnums[0]+nums[1]+...+nums[t-1] = preSumnums[0]+nums[1]+...+nums[t1]=preSum,在这个时刻之前共有HashMap[V]HashMap[V]HashMap[V](V=presum−kV = presum-kV=presumk)个indices jjj 使得nums[0]+nums[1]+...+nums[j]=Vnums[0]+nums[1]+...+nums[j] = Vnums[0]+nums[1]+...+nums[j]=V,且nums[j]+...+nums[t−1]=preSum−Vnums[j]+...+nums[t-1] =preSum- Vnums[j]+...+nums[t1]=preSumV
所以在每个时刻我们都将HashMap[preSum−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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值