1013. 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])

问能不能把数组分成3部分,使得三部分的和相等。

target = sum(A) // 3,从从左往右寻找每一段和等于target的区间。找到第三段的时候,判断下剩下的是不是加和等于0就知道能不能分了。

class Solution(object):
    def canThreePartsEqualSum(self, A):
        """
        :type A: List[int]
        :rtype: bool
        """
        target = sum(A) // 3
        l = 0
        current_sum = 0
        cnt = 0
        for i in range(len(A)):
            current_sum += A[i]
            if current_sum == target:
                current_sum = 0
                cnt += 1
                if cnt == 3:
                    return sum(A[i + 1:]) == 0
原文地址:https://www.cnblogs.com/whatyouthink/p/13232563.html