File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed
0560_subarray_sum_equals_k Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments