[LeetCode] Subarray Sum Equals K

560. Subarray Sum Equals K

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
unordered_map<int, int> m;
m[0]++;
int sum = 0, res = 0;
for(auto& num : nums) {
sum += num;
res += m[sum - k];
m[sum]++;
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/03/PS/LeetCode/subarray-sum-equals-k/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.