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