#include<iostream>
#include<vector>
#include<unordered_map>
using namespace std;
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
unordered_map<int, int> mymap;
mymap[0]=1;
int sum=0;
int ans=0;
for (auto x: nums){
sum+=x;
ans+=mymap[sum-k];
++mymap[sum];
}
return ans;
}
};
int main(){
vector<int> nums={1, 2, 3, 1, 2, 3};
int k=6;
Solution S;
int ans=S.subarraySum(nums, k);
cout<<ans;
return 0;
}
输出结果:
4