题目描述
给你一个整数数组 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
代码示例
static const auto _ = []()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
bool canThreePartsEqualSum(vector<int>& A) {
int s = accumulate(A.begin(), A.end(), 0);
if(s % 3 != 0){
return false;
}
int target = s / 3;
int n = A.size(), i = 0, cur = 0;
while(i < n){
cur += A[i];
if(cur == target){
break;
}
i++;
}
if(cur != target){
return false;
}
int j = i + 1;
//已证明存在target,只需再证明target*2存在即题设成立,但至少保证数组最后一项还存在
while(j + 1 < n){
cur += A[j];
if(cur == target * 2){
return true;
}
++j;
}
return false;
}
};
关于可以提速的代码块
解释看这里
https://blog.csdn.net/weixin_42658928/article/details/82974658