LeetCode解题分享:1013. Partition Array Into Three Parts With Equal Sum

Problem

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:

  1. 3 <= A.length <= 50000
  2. -10000 <= A[i] <= 10000
解题思路

   其实这道题很简单,但是依然有一个值得说的地方,就是判定系统中并不存在一个数据是全部由0组成的,这样如果代码写的不好就会产生一定的错误。因此,我们需要先判断所有数据的和是不是0,如果是0的话,并且数组中存在多个段的和都是0,那么只需要段的数目大于等于3即可,如果所有数据的和结果不是0,那么只需要按照常规判断就好。

   代码如下:

class Solution:
    def canThreePartsEqualSum(self, A: list) -> bool:
        s = sum(A)

        if s % 3 != 0:
            return False

        cnt = 0

        nn = 0
        for n in A:
            if n + cnt == s // 3:
                nn += 1
                cnt = 0
                continue
            cnt += n

        if s == 0:
            return nn >= 3
        else:
            return nn == 3


   一份错误的代码,如果输入是由5个0组成的数据,则会产生错误。

class Solution:
    def canThreePartsEqualSum(self, A: list) -> bool:
        s = sum(A)

        if s % 3 != 0:
            return False

        cnt = 0

        nn = 0
        for n in A:
            if n + cnt == s // 3:
                nn += 1
                cnt = 0
                continue
            cnt += n
            
        return nn == 3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值