Skip to content

Commit 6b9a05f

Browse files
Bruce YangBruce Yang
Bruce Yang
authored and
Bruce Yang
committed
Add C++ solution for day 4(binarysearch924).
1 parent 32cff9c commit 6b9a05f

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <algorithm>
4+
#include <unordered_map>
5+
using namespace std;
6+
7+
int floorMod(const int& a, const int& b)
8+
{
9+
return (a % b + b) % b;
10+
}
11+
int solve(vector<int>& nums, int k) {
12+
int allSum = 0;
13+
for (int& num : nums)
14+
allSum += num;
15+
16+
allSum = floorMod(allSum, k);
17+
unordered_map<int, int> dict; // dict: 某个前缀和%k得到的余数->pos
18+
dict[0] = -1;
19+
20+
int preSum = 0;
21+
int minLen = nums.size();
22+
for (int i = 0; i < nums.size(); i++) {
23+
preSum += nums[i];
24+
int mod = floorMod(preSum, k);
25+
dict[mod] = i;
26+
27+
if (dict.count(floorMod(preSum - allSum, k)))
28+
minLen = min(minLen, i - dict[floorMod(preSum - allSum, k)]);
29+
}
30+
return minLen == nums.size() ? -1 : minLen;
31+
}
32+
33+
// Test
34+
int main()
35+
{
36+
vector<int> A = {1, 8, 6, 4, 5};
37+
int k = 7;
38+
auto res = solve(A, k);
39+
cout << res << endl;
40+
41+
return 0;
42+
}

0 commit comments

Comments
 (0)