给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。
示例 1 :
输入:nums = [1,1,1], k = 2 输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。
说明 :
数组的长度为 [1, 20,000]。
数组中元素的范围是 [-1000, 1000] ,且整数 k 的范围是 [-1e7, 1e7]。
C++
class Solution {
public:
int subarraySum(vector<int>& nums, int k)
{
int n=nums.size();
map<int,int> tmp;
int sum=0;
int ans=0;
tmp[0]=1;
for(int i=0;i<n;i++)
{
sum+=nums[i];
ans+=tmp[sum-k];
tmp[sum]++;
}
return ans;
}
};
python
class Solution:
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
n=len(nums)
res=0
dic={0:1}
su=0
for i in range(n):
su+=nums[i]
if (su-k) in dic:
res+=dic[su-k]
if su not in dic:
dic[su]=1
else:
dic[su]+=1
return res