LeetCode] [1013. Partition Array Into Three Parts With Equal Sum and the array is divided into three equal portions (Easy) (JAVA)

LeetCode] [1013. Partition Array Into Three Parts With Equal Sum and the array is divided into three equal portions (Easy) (JAVA)

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

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

1. 3 <= A.length <= 50000
2. -10^4 <= A[i] <= 10^4

Subject to the effect

To give you an array of integers A, can only return it into three equal and non-null only part true, otherwise false.

Formally, if we can find the index i + 1 <j satisfying (A [0] + A [1] + ... + A [i] == A [i + 1] + A [i + 2] + ... + A [j-1] == A [j] + A [j-1] + ... + A [A.length - 1]) can be an array of three aliquots.

Problem-solving approach

1, and the array element SUM
2, traversed successively find sum / 3 -> sum / 3 * 2 two nodes
note: sum = special attention 0

class Solution {
    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;
        int cur = 0;
        boolean first = false;
        for (int i = 0; i < A.length; i++) {
            cur += A[i];
            if (!first && cur == sum / 3) {
                first = true;
                continue;
            }
            if (first && cur == sum / 3 * 2 && i < (A.length - 1)) return true;
        }
        return false;
    }
}

When execution: 1 ms, defeated 100.00% of all users to submit in Java
memory consumption: 45 MB, defeated 100.00% of users in all Java submission

Published 81 original articles · won praise 6 · views 2287

Guess you like

Origin blog.csdn.net/qq_16927853/article/details/104789555
Recommended