1013.Partition Array Into Three Parts With Equal Sum(将数组分成和相等的三个部分)

Description

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


给定一个整数数组 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]) 就可以将数组三等分。

题目链接:https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/

Difficulty: easy

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整除,返回False,tar=sum(A)/3;
  • index记录当前遍历所有的数字的和,s为和为tar的序列数;
  • 遍历A,index加上当前数字,若index等于tar,s加一,index置零;
  • 若s等于3返回True,反之False。

参考代码

class Solution(object):
def canThreePartsEqualSum(self, A):
    N=len(A)
    tar=sum(A)//3
    if(tar*3!=sum(A)):
        return False
    index=0
    s=0
    for i in range(N):
        index+=A[i]
        if(index==tar):
            index=0
            s+=1
    if(s==3):
        return True
    return False
-------------本文结束你这么美,还坚持读完了-------------