1013. Partition Array Into Three Parts With Equal Sum*
https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/
题目描述
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
C++ 实现 1
双指针, 判断 A[0... i]
范围内的元素和 A[j ... N - 1]
范围内的元素是否同时等于 sum / 3
class Solution {
public:
bool canThreePartsEqualSum(vector<int>& A) {
int sum = std::accumulate(A.begin(), A.end(), 0);
int i = 0, j = A.size() - 1;
int part1 = 0, part3 = 0;
int target = sum / 3;
// 注意这里不要写成 i + 1 < j, 因为 i 最后满足 part1 == target 的条件之后
// 还要进行 ++ 操作.
while (i < j) {
if (part1 != target)
part1 += A[i++];
else if (part3 != target) part3 += A[j--];
if (part1 == target && part3 == target) return true;
}
return false;
}
};