-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0930.cpp
More file actions
37 lines (31 loc) · 854 Bytes
/
Copy path0930.cpp
File metadata and controls
37 lines (31 loc) · 854 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
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
public:
int numSubarraysWithSum(const vector<int> &nums, int goal) const {
unordered_map<int, int> um = {{0, 1}};
int res = 0, crnt = 0;
for (const int n : nums) {
crnt += n;
res += um[crnt - goal];
um[crnt]++;
}
return res;
}
};
// O(1) space
class Solution {
int atMost(const vector<int> &nums, int goal) const {
if (goal < 0) return 0;
int res = 0, crnt = 0, i = 0;
for (int j = 0; j < size(nums); j++) {
goal -= nums[j];
while (goal < 0)
goal += nums[i++];
res += j - i + 1;
}
return res;
}
public:
int numSubarraysWithSum(const vector<int> &nums, int goal) const {
return atMost(nums, goal) - atMost(nums, goal - 1);
}
};