[LeetCode] 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

解题思路

要能够分为三部分,首先需要总和能够被3整除。然后如果保证左侧的总和跟中间的总和都是等于数组总和的三分之一,就说明可以分为三部分。

实现代码

// Runtime: 1 ms, faster than 100.00% of Java online submissions for Partition Array Into Three Parts With Equal Sum.
// Memory Usage: 50.7 MB, less than 100.00% of Java online submissions for Partition Array Into Three Parts With Equal Sum.
class Solution {
    public boolean canThreePartsEqualSum(int[] A) {
        int sum = 0;
        for (int i = 0; i < A.length; i++) {
            sum += A[i];
        }
        
        if (sum % 3 != 0) {
            return false;
        }
        
        int leftSum = 0, midSum = 0;
        for (int i = 0; i < A.length; i++) {
            if (leftSum == sum / 3) {
                if (midSum == sum / 3) {
                    return true;
                } else {
                    midSum += A[i];
                }
            } else {
                leftSum += A[i];
            }
        }
        
        return false;
    }
}

你可能感兴趣的:([LeetCode] Partition Array Into Three Parts With Equal Sum)