Given an array A of integers, return true if and only if we can partition the array into three non-empty parts with equal sums.
Formally, we can partition the array if we can find indexes i+1 < j with (A[0] + A[1] + … + A[i] == A[i+1] + A[i+2] + … + A[j-1] == A[j] + A[j-1] + … + A[A.length - 1])
Example 1:
Input: [0,2,1,-6,6,-7,9,1,2,0,1]
Output: true
Explanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1
Example 2:
Input: [0,2,1,-6,6,7,9,-1,2,0,1]
Output: false
Example 3:
Input: [3,3,6,5,-2,2,5,1,-9,4]
Output: true
Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4
Note:
3 <= A.length <= 50000
-10000 <= A[i] <= 10000
难度:easy
解题思路:
若序列能分成总和相等的三个子序列,则先要保证总和能被3整除,这个是第51个测试点,然后此题需要用空间换时间,将计算的和值保存下来,这样可以将时间复杂度降低至O(n).
代码:
class Solution {
public:
bool canThreePartsEqualSum(vector<int>& A) {
int len=A.size();
vector<int> sum(len,0);
sum[0]=A[0];
for(int i=1;i<len;i++){
sum[i]=sum[i-1]+A[i];
}
int r1=-1,r2=-1;
if(sum[len-1]%3) return false;
for(int i=0;i<len;i++){
if(sum[len-1]/3==sum[i]){
r1=i;
break;
}
}
if(r1==-1) return false;
for(int i=r1+1;i<len;i++){
if(2*sum[len-1]/3==sum[i]){
r2=i;
break;
}
}
return r2!=-1;
}
};