# lc560. Subarray Sum Equals K

Contents

Given an array of integers `nums` and an integer `k`, return the total number of continuous subarrays whose sum equals to `k`.

Example 1:

 ``````1 2 `````` ``````Input: nums = [1,1,1], k = 2 Output: 2 ``````

Example 2:

 ``````1 2 `````` ``````Input: nums = [1,2,3], k = 3 Output: 2 ``````

Constraints:

• `1 <= nums.length <= 2 * 104`
• `-1000 <= nums[i] <= 1000`
• `-107 <= k <= 107`
###### 解题思路：

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 `````` ``````class Solution(object): def subarraySum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ cumulative=[0] base=0 for num in nums: base+=num cumulative.append(base) ans=0 for i in range(len(cumulative)-1): for j in range(i+1,len(cumulative)): res=cumulative[j]-cumulative[i] if res==k: ans+=1 return ans ``````

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 `````` ``````class Solution(object): def subarraySum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ ans=0 for i in range(len(nums)-1): sum=0 for j in range(i,len(nums)): sum+=nums[j] if sum==k: ans+=1 return ans ``````

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 `````` ``````class Solution(object): def subarraySum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ _sum, res, cul = 0, 0, {0:1} for _ in nums: _sum+=_ if _sum-k in cul: res+=cul[_sum-k] try: cul[_sum]+=1 except: cul[_sum]=1 return res ``````