-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path560.subarray-sums-equal-k.cpp
More file actions
57 lines (53 loc) · 1.04 KB
/
560.subarray-sums-equal-k.cpp
File metadata and controls
57 lines (53 loc) · 1.04 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution
{
public:
int subarraySum(vector<int> &nums, int k)
{
int count = 0;
for (int start = 0; start < nums.size(); ++start)
{
int sum = 0;
for (int end = start; end < nums.size(); ++end)
{
sum += nums[end];
if (sum == k)
{
++count;
}
}
}
return count;
}
};
class Solution2
{
public:
int subarraySum(vector<int> &nums, int k)
{
int count = 0;
unordered_map<int, int> map;
map[0]++;
int sum = 0;
for (int i = 0; i < nums.size(); ++i)
{
sum += nums[i];
if (map[sum - k])
{
count += map[sum - k];
}
map[sum]++;
}
return count;
}
};
int main()
{
Solution s;
vector<int> v = {1, 1, 1};
s.subarraySum(v, 2);
return 0;
}