Partition Array Into Three Parts With Equal Sum
Given an array of integers arr, return true 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 (arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1])
Example 1:
Input: arr = [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: arr = [0,2,1,-6,6,7,9,-1,2,0,1]
Output: false
Example 3:
Input: arr = [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 <= arr.length <= 5 * 104
-104 <= arr[i] <= 104
思路一:数组分三段,分别统计这三段的值,注意每段求和的时候需要提前赋值
public static boolean canThreePartsEqualSum(int[] arr) {
int sum = 0;
for (int i : arr) {
sum += i;
}
if (sum % 3 != 0) {
return false;
}
int val = sum / 3;
int begin = 0;
int end = arr.length - 1;
int partOne = arr[begin++];
while (partOne != val && begin <= end) {
partOne += arr[begin];
begin++;
}
int partThree = arr[end--];
while (partThree != val && end >= 0) {
partThree += arr[end];
end--;
}
if (begin > end) {
return false;
}
int parTwo = arr[begin++];
while (begin <= end) {
parTwo += arr[begin];
begin++;
}
return partOne == parTwo && parTwo == partThree;
}
思路二:看了一下题解,中间那段不用计算,如果首尾的和相等,中间那段也一定相等
标签:arr,end,int,sum,begin,easy,false,leetcode,1013 From: https://www.cnblogs.com/iyiluo/p/17413212.html