forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
three-equal-parts.cpp
36 lines (33 loc) · 890 Bytes
/
three-equal-parts.cpp
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
// Time: O(n)
// Space: O(1)
class Solution {
public:
vector<int> threeEqualParts(vector<int>& A) {
int total = accumulate(A.cbegin(), A.cend(), 0);
if (total % 3 != 0) {
return {-1, -1};
}
if (total == 0) {
return {0, A.size() - 1};
}
const auto count = total / 3;
vector<int> nums(3);
int c = 0;
for (int i = 0; i < A.size(); ++i) {
if (A[i] == 1) {
if (c % count == 0) {
nums[c / count] = i;
}
++c;
}
}
while (nums[2] != A.size()) {
if (A[nums[0]] != A[nums[1]] ||
A[nums[0]] != A[nums[2]]) {
return {-1, -1};
}
++nums[0], ++nums[1], ++nums[2];
}
return {nums[0] - 1, nums[1]};
}
};