File tree Expand file tree Collapse file tree 4 files changed +87
-0
lines changed Expand file tree Collapse file tree 4 files changed +87
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Solve Time : 30:20
3
+
4
+ Time : O(N^2)
5
+ Space : O(N)
6
+
7
+ まず素朴にO(N^3)の解法を思いつき、次にそれを効率化するO(N^2)の解法を思いつく。
8
+ それをmapでもう一段階高速化できそうと思い実装したがこんがらがって時間がかかりすぎてしまったのでひとまずO(N^2)の解法で解く。
9
+ */
10
+ class Solution {
11
+ public:
12
+ int subarraySum (vector<int >& nums, int k) {
13
+ vector<int > cumulative_nums = {0 };
14
+ for (int num : nums) {
15
+ cumulative_nums.push_back (cumulative_nums.back () + num);
16
+ }
17
+ int subarray_count = 0 ;
18
+ for (int i = 0 ; i < cumulative_nums.size (); ++i) {
19
+ for (int j = i + 1 ; j < cumulative_nums.size (); ++j) {
20
+ if (cumulative_nums[j] - cumulative_nums[i] == k) {
21
+ subarray_count++;
22
+ }
23
+ }
24
+ }
25
+ return subarray_count;
26
+ }
27
+ };
Original file line number Diff line number Diff line change
1
+ /*
2
+ Time : O(N log N)
3
+ Space : O(N)
4
+
5
+ step1で解けなかったO(N log N)の解法。
6
+ 色々思考を整理して書いたところ問題なく行けた。
7
+ このあたりの思考スピードが課題。
8
+ */
9
+ class Solution {
10
+ public:
11
+ int subarraySum (vector<int >& nums, int k) {
12
+ vector<int > cumulative_nums = {0 };
13
+ for (int num : nums) {
14
+ cumulative_nums.push_back (cumulative_nums.back () + num);
15
+ }
16
+ int subarray_count = 0 ;
17
+ map<int , int > cumulative_num_to_count;
18
+ for (int i = cumulative_nums.size () - 1 ; i > 0 ; --i) {
19
+ cumulative_num_to_count[cumulative_nums[i]]++;
20
+ subarray_count += cumulative_num_to_count[k + cumulative_nums[i - 1 ]];
21
+ }
22
+ return subarray_count;
23
+ }
24
+ };
Original file line number Diff line number Diff line change
1
+ /*
2
+ Time : O(N)
3
+ Space : O(N)
4
+
5
+ 他の人のコードを参考にstep2_1を改良したもの。
6
+ 累積和の捉え方に関しては駅と標高の例えがかなりしっくりきた。
7
+ */
8
+ class Solution {
9
+ public:
10
+ int subarraySum (vector<int >& nums, int k) {
11
+ int subarray_count = 0 ;
12
+ int cumulative_num = 0 ;
13
+ map<int , int > cumulative_num_to_count;
14
+ cumulative_num_to_count[0 ] = 1 ;
15
+ for (int num : nums) {
16
+ cumulative_num += num;
17
+ subarray_count += cumulative_num_to_count[cumulative_num - k];
18
+ ++cumulative_num_to_count[cumulative_num];
19
+ }
20
+ return subarray_count;
21
+ }
22
+ };
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ int subarraySum (vector<int >& nums, int k) {
4
+ int subarray_count = 0 ;
5
+ int cumulative_num = 0 ;
6
+ map<int , int > cumulative_num_to_count = {{0 , 1 }};
7
+ for (int num : nums) {
8
+ cumulative_num += num;
9
+ subarray_count += cumulative_num_to_count[cumulative_num - k];
10
+ cumulative_num_to_count[cumulative_num]++;
11
+ }
12
+ return subarray_count;
13
+ }
14
+ };
You can’t perform that action at this time.
0 commit comments