LeetCode-Partition Array Into Three Parts With Equal Sum

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/88837010

Description:
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: [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:

  • 3 <= A.length <= 50000
  • -10000 <= A[i] <= 10000

题意:计算数组A是否能够被 i i , j j i + 1 &lt; j i+1&lt;j )划分为三个部分,这三个部分不为空且所有元素的和相同;

解法:要将数组A划分为相等的三个部分,并且这三个部分的和相同,那么这三个部分的和应该为数组A所有元素和的三分之一(要求可被3整除);但是,题目已经限定了划分的原则是利用 i i , j j i + 1 &lt; j i+1&lt;j )分为三个部分,因此难度就大大降低了,因为不需要考虑对任意位置元素的组合;下面是解题的流程

  1. 计算数组A的和sum
  2. 计算sum是否能被3整除,若不能,则返回false,否则得到三个部分的和为average = sum / 3
  3. for i in range(A.length):
  4. 对元素A[i]求和直到A[i] == average,记录划分数量增加1
  5. 判断划分数量是否为3,是则返回ture,否则返回false;
Java
class Solution {
    public boolean canThreePartsEqualSum(int[] A) {
        int average = 0;
        for (int a: A) {
            average += a;
        }
        if (average % 3 != 0) {
            return false;
        }
        average /= 3;
        int sum = 0;
        int part = 0;
        for (int i = 0; i < A.length; i++) {
            sum += A[i];
            if (sum == average) {
                sum = 0;
                part++;
            }
        }
        
        return part == 3 ? true : false;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/88837010