zoukankan      html  css  js  c++  java
  • [LeetCode]1013. Partition Array Into Three Parts With Equal Sum

    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: A = [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: A = [0,2,1,-6,6,7,9,-1,2,0,1]
    Output: false
    Example 3:

    Input: A = [3,3,6,5,-2,2,5,1,-9,4]
    Output: true
    Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4
     

    Constraints:

    3 <= A.length <= 50000
    -10^4 <= A[i] <= 10^4

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/partition-array-into-three-parts-with-equal-sum
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    python3:

     1 class Solution:
     2     def canThreePartsEqualSum(self, A: List[int]) -> bool:
     3         if sum(A) % 3 != 0:
     4             return False
     5         
     6         avg = sum(A) // 3
     7         i = 0
     8         j = len(A) - 1
     9         sum_f = A[i]
    10         i += 1
    11         sum_b = A[j]
    12         j -= 1
    13         rst = False
    14         
    15         while i < j:
    16             if sum_f != avg:
    17                 sum_f += A[i]
    18                 i += 1
    19             if sum_b != avg:
    20                 sum_b += A[j]
    21                 j -= 1
    22             if sum_f == avg and sum_b == avg:
    23                 rst = True
    24                 break
    25         
    26         if i > j:
    27             rst = False
    28         return rst
  • 相关阅读:
    第3周 实践项目2 建设”顺序表“算法库(可参考为模板)
    第3周实践项目3 求集合并集
    【luogu 2529】【SHOI 2001】击鼓传花
    【BZOJ 3270】博物馆
    【BZOJ 2337】XOR和路径
    浅谈期望dp
    【codeforces 24D】Broken Robot
    【POJ 1463】Strategic game
    【POJ 3585】Accumulation Degree
    【luogu 3146/3147】248/262144
  • 原文地址:https://www.cnblogs.com/dean757/p/12463692.html
Copyright © 2011-2022 走看看