当前位置 : 首页 » 文章分类 :  算法  »  LeetCode.1013.Partition Array Into Three Parts With Equal Sum 将数组分成和相等的三个部分

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/

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


解题过程

将数组分为和相等的三部分,其实就是找两个下标, left 和 right ,使得这两个下标分隔的数组三部分的和相等。
这题一看肯定至少需要 O(n) 的复杂度了,所以不如我们先 O(n) 直接遍历一遍数组求出总和 sum
然后两个指针 left right 分别从左右开始移动,每次比较 left左边、left和right之间、right右边 三部分的和,由于有了总和,中间部分也可以直接得出。
当 三部分和相等时,结束。
当 三部分和不相等时,按规则 移动 left 和 right 指针。规则就是 leftSum 不等于 sum/3 就右移left指针, rightSum 不等于 sum/3 就左移right指针。
时间复杂度 O(n), 空间复杂度 O(1)

private static class SolutionV2020 {
    public boolean canThreePartsEqualSum(int[] nums) {
        if (null == nums || nums.length < 3) {
            return false;
        }
        int sum = 0; // 总和
        for (int n : nums) {
            sum += n;
        }
        if (sum % 3 != 0) { // 无法分为sum相等的3部分
            return false;
        }
        int targetPartSum = sum / 3;
        int left = 0, right = nums.length - 1;
        int leftSum = nums[left], rightSum = nums[right];
        while (left + 1 < right) {
            int midSum = sum - leftSum - rightSum; // 中间部分的和
            if (midSum == leftSum && midSum == rightSum) {
                // 3部分和相等,结束
                System.out.println(left + ": " + nums[left] + ", " + right + ": " + nums[right]);
                return true;
            }
            if (leftSum != targetPartSum) {
                left++;
                leftSum += nums[left];
            }
            if (rightSum != targetPartSum) {
                right--;
                rightSum += nums[right];
            }
        }
        return false;
    }
}

GitHub代码

algorithms/leetcode/leetcode/_1013_PartitionArrayIntoThreePartsWithEqualSum.java
https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_1013_PartitionArrayIntoThreePartsWithEqualSum.java


上一篇 LeetCode.1071.Greatest Common Divisor of Strings 字符串的最大公因子

下一篇 LeetCode.322.Coin Change 零钱兑换

阅读
评论
520
阅读预计3分钟
创建日期 2020-03-11
修改日期 2020-03-11
类别

页面信息

location:
protocol:
host:
hostname:
origin:
pathname:
href:
document:
referrer:
navigator:
platform:
userAgent:

评论