|
| 1 | +/****************************** |
| 2 | +1013. Partition Array Into Three Parts With Equal Sum |
| 3 | + |
| 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. |
| 5 | +Formally, we can partition the array if we can find indexes i+1 < j with |
| 6 | +(A[0] + A[1] + ... + A[i] == A[i+1] + A[i+2] + ... + A[j-1] == A[j] + A[j-1] + ... + A[A.length - 1]) |
| 7 | + |
| 8 | +Example 1: |
| 9 | +Input: [0,2,1,-6,6,-7,9,1,2,0,1] |
| 10 | +Output: true |
| 11 | +Explanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1 |
| 12 | + |
| 13 | +Example 2: |
| 14 | +Input: [0,2,1,-6,6,7,9,-1,2,0,1] |
| 15 | +Output: false |
| 16 | + |
| 17 | +Example 3: |
| 18 | +Input: [3,3,6,5,-2,2,5,1,-9,4] |
| 19 | +Output: true |
| 20 | +Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4 |
| 21 | + |
| 22 | +Note: |
| 23 | +1. 3 <= A.length <= 50000 |
| 24 | +2. -10000 <= A[i] <= 10000 |
| 25 | + |
| 26 | +******************************/ |
| 27 | + |
| 28 | +/****************************** |
| 29 | +1、先遍历一遍,求出数组和,检查总和是否能被3整除; |
| 30 | +2、循环遍历数组A,计算和的一部分partitionSum;如果找到和 sum/3 相等,则将partitionSum重置为0,并增加计数器count; |
| 31 | +3、到最后,如果平均可以看到至少3次,返回true;否则返回false。 |
| 32 | +时间复杂度:O(n) |
| 33 | +空间复杂度:O(1) |
| 34 | +******************************/ |
| 35 | + |
| 36 | + |
| 37 | +class Solution { |
| 38 | + public boolean canThreePartsEqualSum(int[] A) { |
| 39 | + int sum = 0; |
| 40 | + |
| 41 | + for (int num : A) { |
| 42 | + sum += num; |
| 43 | + } |
| 44 | + |
| 45 | + if (sum % 3 != 0) { |
| 46 | + return false; |
| 47 | + } |
| 48 | + |
| 49 | + int count = 0; |
| 50 | + int partitionSum = 0; |
| 51 | + |
| 52 | + for (int i = 0; i < A.length; i ++) { |
| 53 | + partitionSum += A[i]; |
| 54 | + |
| 55 | + if (partitionSum == sum / 3) { |
| 56 | + partitionSum = 0; |
| 57 | + count ++; |
| 58 | + } |
| 59 | + |
| 60 | + if (count >= 3) { |
| 61 | + return true; |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + return false; |
| 66 | + } |
| 67 | +} |
0 commit comments