-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubarraySumK.cpp
More file actions
76 lines (72 loc) · 1.57 KB
/
Copy pathsubarraySumK.cpp
File metadata and controls
76 lines (72 loc) · 1.57 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* https://leetcode.com/problems/subarray-sum-equals-k/
* Array, Hash Table, Prefix Sum
*/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool isSubarraySumK(vector<int>& nums, int k, int start, int end) {
int sum = 0;
for (int i = start; i <= end; i++) {
if (sum >= k) {
return false;
}
sum += nums[i];
}
if (sum == k) {
return true;
}
return false;
}
int subarraySum(vector<int>& nums, int k) {
int count = 0;
int start = 0;
int end = 1;
int currSum = nums[0];
while (start < nums.size() - 1 && end < nums.size() - 1) {
cout << currSum << endl;
if (currSum == k) {
count++;
currSum -= nums[start];
start++;
end++;
currSum += nums[end];
}
else if (currSum < k) {
end++;
currSum += nums[end];
} else {
currSum -= nums[start];
start++;
}
}
return count;
}
};
vector<int> vectorFromArray(int* array, int size) {
vector<int> vector;
for (int i = 0; i < size; i++) {
vector.push_back(array[i]);
}
return vector;
}
int main() {
int numsSize, k;
cout << "Input size of array: ";
cin >> numsSize;
int *numsArr = new int[numsSize];
cout << "Input nums:" << endl;
int num;
for (int i = 0; i < numsSize; i++) {
cin >> num;
numsArr[i] = num;
}
cout << "Input k: ";
cin >> k;
vector<int> nums = vectorFromArray(numsArr, numsSize);
Solution solution;
int output = solution.subarraySum(nums, k);
cout << "Total number of subarrays whose sum equals to k: " << output << endl;
}