Skip to content

Commit f28a3c6

Browse files
authored
Create continuous-subarray-sum.cpp
1 parent a098e33 commit f28a3c6

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

C++/continuous-subarray-sum.cpp

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Time: O(n)
2+
// Space: O(k)
3+
4+
class Solution {
5+
public:
6+
bool checkSubarraySum(vector<int>& nums, int k) {
7+
int count = 0;
8+
unordered_map<int, int> lookup;
9+
lookup[0] = -1;
10+
for (int i = 0; i < nums.size(); ++i) {
11+
count += nums[i];
12+
if (k != 0) {
13+
count %= k;
14+
}
15+
if (lookup.count(count)) {
16+
if (i - lookup[count] > 1) {
17+
return true;
18+
}
19+
} else {
20+
lookup[count] = i;
21+
}
22+
}
23+
return false;
24+
}
25+
};

0 commit comments

Comments
 (0)