Description
https://leetcode.com/problems/subarray-sum-equals-k/
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].
Explanation
store complement to help counting
Python Solution
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
count = 0
sum = 0
map = {}
map[0] = 1
for i in range(0, len(nums)):
sum += nums[i]
if (sum - k) in map:
count += map.get(sum - k)
map[sum] = map.get(sum, 0) + 1
return count
- Time complexity: O(N).
- Space complexity: O(N).
test