forked from larissalages/code_problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path560.cpp
More file actions
24 lines (17 loc) · 759 Bytes
/
560.cpp
File metadata and controls
24 lines (17 loc) · 759 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int n= nums.size(),i, cumSum= 0, res=0;
unordered_map<int,int> m;//<sum till now,count>
m[0]= 1;
for (i=0;i<n;i++){
cumSum+=nums[i];//update the cumulative sum or the sum of prefix subarray till the curr elem
res+=m[cumSum-k];//find the required sum and update the result, if it doesnt exist it will return 0
m[cumSum]++;//update the cumulative sum
}
return res;
}
};
//======================================================
//Time complexity of the above algorith: O(n), n is the length of the input array
//Space complexity: O(n), because of the hashmap