Given an array of integers nums
and an integer k
, return the total number of continuous subarrays whose sum equals to k
.
Example 1:
Input: nums = [1,1,1], k = 2 Output: 2
Example 2:
Input: nums = [1,2,3], k = 3 Output: 2
Constraints:
1 <= nums.length <= 2 * 104
-1000 <= nums[i] <= 1000
-107 <= k <= 107
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
mp = collections.Counter()
mp[0] = 1
res = s = 0
for num in nums:
s += num
res += mp[s - k]
mp[s] += 1
return res
class Solution {
public int subarraySum(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 1);
int res = 0;
int s = 0;
for (int num : nums) {
s += num;
res += map.getOrDefault(s - k, 0);
map.put(s, map.getOrDefault(s, 0) + 1);
}
return res;
}
}
function subarraySum(nums: number[], k: number): number {
let ans = 0, pre = 0;
let hashTable = new Map();
hashTable.set(0, 1);
for (let num of nums) {
pre += num;
ans += (hashTable.get(pre - k) || 0);
hashTable.set(pre, (hashTable.get(pre) || 0) + 1);
}
return ans;
};
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
unordered_map<int, int> mp;
mp[0] = 1;
int res = 0, s = 0;
for (int num : nums)
{
s += num;
res += mp[s - k];
++mp[s];
}
return res;
}
};
func subarraySum(nums []int, k int) int {
mp := make(map[int]int)
mp[0] = 1
res, s := 0, 0
for _, num := range nums {
s += num
res += mp[s-k]
mp[s]++
}
return res
}