LeetCode 1013. 将数组分成和相等的三个部分 Partition Array Into Three Parts With Equal Sum
Table of Contents
一、中文版
给你一个整数数组 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]) 就可以将数组三等分。
示例 1:
输出:[0,2,1,-6,6,-7,9,1,2,0,1]
输出:true
解释:0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1
示例 2:
输入:[0,2,1,-6,6,7,9,-1,2,0,1]
输出:false
示例 3:
输入:[3,3,6,5,-2,2,5,1,-9,4]
输出:true
解释:3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4
提示:
3 <= A.length <= 50000
-10^4 <= A[i] <= 10^4
二、英文版
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 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
三、My answer
class Solution: def canThreePartsEqualSum(self, A: List[int]) -> bool: if sum(A) % 3 != 0: return False target = sum(A) / 3 if not A: return False sum_ = 0 idx = 0 for i in range(len(A)): sum_ += A[i] if i < len(A)-1: if sum_ == target: idx = i sum_ = 0 break else: return False for i in range(idx+1,len(A)): sum_ += A[i] if i < len(A)-1: if sum_ == target: return True # 以下两个 return false 保留一个即可 # else: # return False return False
四、解题报告
只要找出三段,使每段数字之和等于总数组之和的三分之一即可。
一开始我将题目想复杂了,以为选出来的数字是打乱顺序的,费了好长时间重新审题之后才发现题目中已经说明 (A[0] + A[1] + ... + A[i] == A[i+1] + A[i+2] + ... + A[j-1] == A[j] + A[j-1] + ... + A[A.length - 1]) 。所以一定是按照原顺序划分。可以理解为将数组切两刀使每一部分加和相等,若能找出这两刀的位置则是True,否则 False。