Skip to content

Commit 0431b5e

Browse files
authored
Create three-equal-parts.cpp
1 parent d08e429 commit 0431b5e

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

C++/three-equal-parts.cpp

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
vector<int> threeEqualParts(vector<int>& A) {
7+
int total = accumulate(A.cbegin(), A.cend(), 0);
8+
if (total % 3 != 0) {
9+
return {-1, -1};
10+
}
11+
if (total == 0) {
12+
return {0, A.size() - 1};
13+
}
14+
15+
const auto count = total / 3;
16+
vector<int> nums(3);
17+
int c = 0;
18+
for (int i = 0; i < A.size(); ++i) {
19+
if (A[i] == 1) {
20+
if (c % count == 0) {
21+
nums[c / count] = i;
22+
}
23+
++c;
24+
}
25+
}
26+
27+
while (nums[2] != A.size()) {
28+
if (A[nums[0]] != A[nums[1]] ||
29+
A[nums[0]] != A[nums[2]]) {
30+
return {-1, -1};
31+
}
32+
++nums[0], ++nums[1], ++nums[2];
33+
}
34+
return {nums[0] - 1, nums[1]};
35+
}
36+
};

0 commit comments

Comments
 (0)