给你一个整数数组 A,只有可以将其划分为三个和相等的非空部分时才返回 true,否则返回 false。
形式上,如果可以找出索引 i+1 < j 且满足 (A[0] + A[1] + ... + A[i] == A[i+1] + A[i+2] + ... + A[j-1] == A[j] + A[j-1] + ... + A[A.length - 1]) 就可以将数组三等分。
示例 1:
输出:[0,2,1,-6,6,-7,9,1,2,0,1]
输出:true
解释:0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1
示例 2:
输入:[0,2,1,-6,6,7,9,-1,2,0,1]
输出:false
示例 3:
输入:[3,3,6,5,-2,2,5,1,-9,4]
输出:true
解释:3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4
提示:
3 <= A.length <= 50000
-10^4 <= A[i] <= 10^4
每日打卡:
#include
#include
using namespace std;
class Solution {
public:
bool canThreePartsEqualSum(vector& A) {
int flag1 = false;
int flag2 = false;
int flag3 = false;
int aver = 0;
for (int i = 0; i < A.size(); i++) {
aver += A[i];
}
if (aver % 3 != 0)
return false;
aver /= 3;
int i = 0;
int sum = 0;
for (i = 0; i < A.size(); i++) {
sum += A[i];
if (sum == aver) {
flag1 = true;
break;
}
}
int j = 0;
sum = 0;
for (j = i + 1; j < A.size(); j++) {
sum += A[j];
if (sum == aver) {
flag2 = true;
break;
}
}
int k = 0;
sum = 0;
for (k = j + 1; k < A.size(); k++) {
sum += A[k];
}
if (sum == aver && (j != A.size() - 1)) {
flag3 = true;
}
return (flag1 && flag2 && flag3);
}
private:
void quicksort(vector& a, int left, int right) {
int i = left;
int j = right;
int key = a[i];
if (left < right) {
while (i < j) {
while (i < j && a[j] >= key) {
j--;
}
a[i] = a[j];
while (i < j && a[i] <= key) {
i++;
}
a[j] = a[i];
}
a[i] = key;
quicksort(a, left, j - 1);
quicksort(a, i + 1, right);
}
else {
return;
}
}
};
int main() {
vectora1 = { 0,2,1,-6,6,-7,9,1,2,0,1 };
vectora2 = { 1, -1, 1, -1 };
Solution* ps = new Solution();
cout << ps->canThreePartsEqualSum(a2) << endl;
return 0;
}