1013.Partition Array Into Three Parts With Equal Sum¶
Tags: Easy
Array
Links: 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: A = [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: A = [0,2,1,-6,6,7,9,-1,2,0,1]
Output: false
Example 3:
Input: A = [3,3,6,5,-2,2,5,1,-9,4]
Output: true
Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4
Constraints:
3 <= A.length <= 50000
-10^4 <= A[i] <= 10^4
class Solution {
public:
bool canThreePartsEqualSum(vector<int>& A) {
std::ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n = A.size();
vector<int> preSum(n + 1, 0);
for (int i = 1; i <= n; ++i) {
preSum[i] = preSum[i - 1] + A[i - 1];
}
int sum = preSum[n];
if (sum % 3 != 0) return false;
int avg = sum / 3;
int pos = 0;
if (!search(preSum, 1, n, avg, pos))
return false;
if (!search(preSum, pos + 1, n, 2 * avg, pos))
return false;
if (pos == n) return false;
return true;
}
bool search(const vector<int> & preSum, int start, int end, int target, int & pos)
{
if (start >= end) return false;
for (int i = start; i < end; ++i) {
if (preSum[i] == target) {
pos = i;
return true;
}
}
return false;
}
};
首先计算出数组的前缀和,然后判断其是否整除3。然后在前缀和中寻找avg
,2*avg
,注意寻找2*avg
一定是在找到avg
的位置往后寻找。时间复杂度O(n),空间复杂度O(n)。
最重要的一点是,数组里面的数据并不都是非负数,所以不能用二分查找。
之所以需要检查pos == n
,是考虑1,-1,1,-1
的情况。
另外注意到,其实并不一定要额外占用O(n)的空间存储前缀和,只需一个变量存储从数组开始到当前位置的和。
class Solution {
int pos, preSum;
public:
bool canThreePartsEqualSum(vector<int>& A) {
std::ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n = A.size();
int sum = 0;
for (auto e : A) sum += e;
if (sum % 3 != 0) return false;
int avg = sum / 3;
if (!search(A, 0, n, avg))
return false;
if (!search(A, pos + 1, n, 2 * avg))
return false;
if (pos == n - 1) return false;
return true;
}
bool search(const vector<int> &A, int start, int end, int target)
{
if (start >= end) return false;
for (int i = start; i < end; ++i) {
preSum += A[i];
if (preSum == target) {
pos = i;
return true;
}
}
return false;
}
};
Runtime: 20 ms, faster than 100.00% of C++ online submissions for Partition Array Into Three Parts With Equal Sum.
Memory Usage: 11.9 MB, less than 100.00% of C++ online submissions for Partition Array Into Three Parts With Equal Sum.