leetcode 1013. Partition Array Into Three Parts With Equal Sum( Python )

描述

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.php

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

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:less

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:yii

3 <= A.length <= 50000
-10000 <= A[i] <= 10000
复制代码

解析

先检查总数是否能被 3 整除,而后遍历数组 A 的时候计算部分元素的和,若是找到平均值,则将变量重置为0,并增长计数器,到最后,若是平都可以看到至少3次,返回true,不然返回假。时间复杂度为 O(N),空间复杂度为 O(1)。svg

解答

class Solution(object):
def canThreePartsEqualSum(self, A):
    """
    :type A: List[int]
    :rtype: bool
    """
    if len(A)==3:return True
    total = sum(A)
    if total%3 != 0:return False
    tmp = 0
    count = 0
    for i in A:
        tmp += i
        if tmp != total/3:
            continue
        else:
            count += 1
            tmp = 0
    return count==3
复制代码

运行结果

Runtime: 280 ms, faster than 91.14% of Python online submissions for Partition Array Into Three Parts With Equal Sum.
Memory Usage: 17.6 MB, less than 18.62% of Python online submissions for Partition Array Into Three Parts With Equal Sum.
复制代码

每日格言:每一个人都有属于本身的一片森林,迷失的人迷失了,相逢的人会再相逢。ui

感谢支持
支付宝

支付宝

微信

微信
相关文章
相关标签/搜索