【leetcode】1020. 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-emptyparts 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

解题思路:要使得Input能均分成三段,那么Input所有元素的和一定是3的倍数,这里记为3X。假设下标i和j为第一段和第二段的终点,那么有sum(Input[0:i]) = X,sum(Input[0:j]) = 2X。所以只需要用字典记录整个Input从下标0开始到结束每一段的和,判断和是否能被3整除,以及X和2X是否存在并且X出现在2X之前即可。

代码如下:

class Solution(object):
    def canThreePartsEqualSum(self, A):
        """
        :type A: List[int]
        :rtype: bool
        """
        dic = {}
        total = 0
        for i,v in enumerate(A):
            total += v
            if total not in dic:
                dic[total] = [i]
            elif len(dic[total]) == 1:
                dic[total] += [i]
            else:
                dic[total][-1] = i
        return total % 3 == 0 and total / 3 in dic and total / 3 * 2 in dic and dic[total/3][0] < dic[total / 3 * 2][-1]

猜你喜欢

转载自www.cnblogs.com/seyjs/p/10598257.html