-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContinuous_Subarray_Sum.cpp
More file actions
33 lines (28 loc) · 965 Bytes
/
Continuous_Subarray_Sum.cpp
File metadata and controls
33 lines (28 loc) · 965 Bytes
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
#include <unordered_map>
#include <vector>
class Solution {
public:
bool checkSubarraySum(std::vector<int>& nums, int k) {
std::unordered_map<int, int> remainders;
remainders[nums[0] % k] = 0;
int totalSum = nums[0];
int len = nums.size();
for (int i=1; i<len; i++) {
totalSum += nums[i];
// If the accumulated sum is a perfect multiple of k
if (totalSum % k == 0) {
return true;
}
// If there already exists a prefix sum whose remainder sum % k is equal to the current remainder
if (remainders.find(totalSum % k) != remainders.end()) {
if (i - remainders[totalSum % k] >= 2) {
return true;
}
}
if (remainders.find(totalSum % k) == remainders.end()) {
remainders[totalSum % k] = i;
}
}
return false;
}
};