https://leetcode.com/problems/subarray-sum-equals-k/
2.Idea
Using map for every sum of {0..i} and count.
3.Source
class Solution {
public:
map<int, int> mp;
int sum = 0;
int subarraySum(vector<int>& nums, int k) {
int ans = 0;
mp[0] = 0;
for (int i = 0; i < nums.size(); i++) {
sum += nums[i];
if(sum == k) ans++;
mp[sum]++;
if (mp.find(sum - k) != mp.end()) {
ans += mp[sum - k];
}
}
if(k == 0) return ans - nums.size();
else return ans;
}
};
No comments:
Post a Comment