LeetCode 1013 Partition Array Into Three Parts With Equal Sum 解题报告

时间:2022-09-12 10:51:32

题目要求

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

题目分析及思路

给定一个整数数组,若该数组能分成三个非空数组且各数组的和相等,则返回true。划分数组时不改变原数组的顺序。可以先确定数组的和是否是3的倍数,若是则获取和的1/3值存为s_t。之后遍历数组依次求和。要求先获得s_t值再获取2*s_t值。若能满足要求则返回true。

python代码

class Solution:

    def canThreePartsEqualSum(self, A: List[int]) -> bool:

        if sum(A) % 3 == 0:

            s_t = sum(A) / 3

            count, flag1, flag2 = 0, 0, 0

            for i in A:

                count += i

                if count == s_t:

                    flag1 = 1

                if count == 2*s_t and flag1 == 1:

                    flag2 = 1

            if flag1 == 1 and flag2 == 1:

                return True

            else:

                return False

        else:

            return False