LeetCode 1013. Partition Array Into Three Parts With Equal Sum

Posted Cheng~

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 1013. Partition Array Into Three Parts With Equal Sum相关的知识,希望对你有一定的参考价值。

1013. Partition Array Into Three Parts With Equal Sum(将数组分成和相等的三个部分)

链接

https://leetcode-cn.com/problems/partition-array-into-three-parts-with-equal-sum

题目

给你一个整数数组?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

思路

普通的数组题,最多多挖了几个坑。
首先统计整个数组的和,如果能被三整除就进行下一步。
从前从后同时开始,如果部分和等于总数的三分之一,那么就不在前进,等到两边都为1/3,中间自然也是1/3.

代码

  public boolean canThreePartsEqualSum(int[] A) {
    int sum = 0;
    for (int i = 0; i < A.length; i++) {
      sum += A[i];
    }
    if (sum % 3 != 0) {
      return false;
    }
    sum = sum / 3;
    int suma = A[0], sumc = A[A.length - 1];
    int i = 1, j = A.length - 2;
    while (i < j) {
      if (suma != sum) {
        suma += A[i++];
      }
      if (sumc != sum) {
        sumc += A[j--];
      }
      if (suma == sum && sumc == sum && i <= j) {
        return true;
      }
    }
    return false;
  }

以上是关于LeetCode 1013. Partition Array Into Three Parts With Equal Sum的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode --- 1013. Partition Array Into Three Parts With Equal Sum 解题报告

leetcode_easy_array1013. Partition Array Into Three Parts With Equal Sum

1013. Partition Array Into Three Parts With Equal Sum

LeetCode Partition List

leetcode 之Partition List(16)

*Leetcode 763. Partition Labels