1013. 将数组分成和相等的三个部分
为保证权益,题目请参考 1013. 将数组分成和相等的三个部分(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
bool canThreePartsEqualSum(vector<int> &A)
{
long long sum = 0;
for (int x : A)
{
sum += x;
}
if (sum % 3 != 0)
{
return false;
}
long long ans = sum / 3;
long long ans_tmp = 0;
int correct_time = 0;
for (int x : A)
{
ans_tmp += x;
if (ans_tmp == ans)
{
ans_tmp = 0;
correct_time++;
}
}
if ((correct_time == 3 && ans_tmp == 0) || (correct_time >3 && ans == 0))
{
return true;
}
return false;
}
};
int main()
{
vector<int> vec;
vec.push_back(3);
vec.push_back(3);
vec.push_back(6);
vec.push_back(5);
vec.push_back(-2);
vec.push_back(2);
vec.push_back(5);
vec.push_back(1);
vec.push_back(-9);
vec.push_back(4);
Solution so;
cout << so.canThreePartsEqualSum(vec);
return 0;
}
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60