给你一个整数数组 A,只有可以将其划分为三个和相等的非空部分时才返回 true,否则返回 false。
形式上,如果可以找出索引 i+1 < j 且满足 (A[0] + A[1] + … + A[i] == A[i+1] + A[i+2] + … + A[j-1] == A[j] + A[j-1] + … + A[A.length - 1]) 就可以将数组三等分。
输出:[0,2,1,-6,6,-7,9,1,2,0,1]
输出:true
解释:0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1
输入:[0,2,1,-6,6,7,9,-1,2,0,1]
输出:false
输入:[3,3,6,5,-2,2,5,1,-9,4]
输出:true
解释:3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4
1. 3 <= A.length <= 50000
2. -10^4 <= A[i] <= 10^4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/partition-array-into-three-parts-with-equal-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码如下:
class Solution:
def canThreePartsEqualSum(self, A: List[int]) -> bool:
sum_A = sum(A)
if sum_A%3 != 0:
return False
average = sum_A/3
sum_average = 0
count = 0
while A:
last = A.pop()
sum_average = sum_average + last
if sum_average == average:
sum_average = 0
count += 1
return True if sum_average==0 and count >= 3 else False
测试结果:
上述代码,可以在遍历循环取值的时候稍加改动。代码如下:
class Solution:
def canThreePartsEqualSum(self, A: List[int]) -> bool:
sum_A = sum(A)
if sum_A%3 != 0:
return False
average = sum_A/3
sum_average = 0
count = 0
for i in A:
sum_average = sum_average + i
if sum_average == average:
sum_average = 0
count += 1
return True if sum_average==0 and count >= 3 else False
这道题思路很清晰,关键要注意最后count的值是大于等于3而不是等于3,这样的原因是防止类似[10,-10,10,-10,10,-10,10,-10]这样的数组出现。这种数组可以分解成4个和为0的数组也可以分解成3个,也是满足条件的。