Skip to content

Commit ccdab52

Browse files
committed
Add solve with exclusive_scan
1 parent 23d06a9 commit ccdab52

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

560/step2_1_fix.cpp

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/*
2+
exclusive_scanを使用して累積和配列を作成したパターン。
3+
また、変数による名前付けでコードを読みやすくしている。
4+
*/
5+
class Solution {
6+
public:
7+
int subarraySum(vector<int>& nums, int k) {
8+
vector<int> cumulative_nums(nums.size());
9+
exclusive_scan(nums.begin(), nums.end(), cumulative_nums.begin(), 0);
10+
cumulative_nums.push_back(cumulative_nums.back() + nums.back());
11+
12+
int subarray_count = 0;
13+
map<int, int> cumulative_num_to_count;
14+
for (int i = cumulative_nums.size() - 1; i > 0; --i) {
15+
cumulative_num_to_count[cumulative_nums[i]]++;
16+
int from_cumulative_num = cumulative_nums[i - 1];
17+
subarray_count += cumulative_num_to_count[from_cumulative_num + k];
18+
}
19+
return subarray_count;
20+
}
21+
};

0 commit comments

Comments
 (0)