Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 545e87d

Browse files
Add new problem
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent bda342c commit 545e87d

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
class Solution {
6+
public:
7+
int subarraySum(vector<int>& nums, int k) {
8+
int res = 0, sum = 0;
9+
unordered_map<int, int> pre_sum_cnt;
10+
11+
// The prefix sum array records the sum of nums[0...i], so we have
12+
// presum[j] - presum[j] = k when the sum of nums[i...j] equals k.
13+
// The presum[0] should always be 0. And pre_sum_cnt[0] = 1.
14+
pre_sum_cnt[0] = 1;
15+
for (const auto n : nums) {
16+
// Here the sum means sum of nums[0...j] and the sum0 means sum
17+
// of nums[0...i] then there will be sum - sum0 = k.
18+
sum += n;
19+
int sum0 = sum - k;
20+
if (ht.count(sum0)) {
21+
res += pre_sum_cnt[sum0];
22+
}
23+
pre_sum_cnt[sum]++;
24+
}
25+
26+
return res;
27+
}
28+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /