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
Idea 1: S + S +... = 3*S = S + S + (-S) + S + S
Time complexity: O(n), 2 scan
Space complexity: O(1)
1 class Solution { 2 public boolean canThreePartsEqualSum(int[] A) { 3 int totalSum = 0; 4 for(int num: A) { 5 totalSum += num; 6 } 7 8 if(totalSum%3 != 0) { 9 return false; 10 } 11 12 int target = totalSum/3; 13 14 int part = 0; 15 int sum = 0; 16 for(int i = 0; i < A.length; ++i) { 17 sum += A[i]; 18 if(sum == target) { 19 ++part; 20 if(part >= 2) { 21 return true; 22 } 23 sum = 0; 24 } 25 26 } 27 28 return false; 29 } 30 }
Partition Array Into Three Parts With Equal Sum LT1013
原文:https://www.cnblogs.com/taste-it-own-it-love-it/p/10634303.html