1013. Partition Array Into Three Parts With Equal Sum

问题:

给定数组,如果刚好将数组分成三段,使得每一段的和相等,则返回true,否则返回false

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

  

  

解法:

首先求数组和sum

然后遍历数组,累加tmp

如果tmp*3==sum,那么到目前的元素,可划分为一组,同时清空tmp=0,计数组数cout++

如果cout>=3后,不再清空tmp

遍历完毕数组后,如果tmp==0且cout==3,满足题意返回true。

如果tmp!=0或者cout!=3

那么,最后一组不能满足=sum/3整除的条件,

或是分组不够3组。则需要返回false。

代码参考:

 1 class Solution {
 2 public:
 3     bool canThreePartsEqualSum(vector<int>& A) {
 4         int sum=0, tmp=0, cout=0;
 5         for(int a:A) sum+=a;
 6         for(int a:A){
 7             tmp+=a;
 8             if(tmp*3==sum && cout<3){
 9                 tmp=0;
10                 cout++;
11             }
12         }
13         return tmp==0 && cout==3;
14     }
15 };
原文地址:https://www.cnblogs.com/habibah-chang/p/13112085.html