The array is divided into three equal portions

The array is divided into three equal portions

problem

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.

Examples

Example 1:

Output: [0,2,1, -6,6, -7,9,1,2,0,1]
Output: true
interpretation: 2 + 0 + 1 = -6 + 6--7 = 2 + 9 + 1 + 0 + 1

Example 2:

Input: [0,2,1, -6,6,7,9, -1,2,0,1]
Output: false

Problem-solving ideas

1. Since the three parts is not empty, so when A.length <3, returns to false;
2. summing array, if the modulo 3 and p is not zero, return to false;
3. Make the array three equal parts, and in addition to the array 3, and each part is obtained, it is determined to continue, and if each part has a value equal to the value, returns true, otherwise returns false;

Problem-solving Code

class Solution {
    public boolean canThreePartsEqualSum(int[] A) {
        if(A.length<3)
            return false;
        int sum=0;
        for(int i=0;i<A.length;i++){
            sum=sum+A[i];
        }
        int a=0;
        if(sum!=0){
            if(sum%3!=0)
                return false;
            a=sum/3;
        }
         int b=0;
        int c=0;
        for(int j=0;j<A.length;j++){
            b=b+A[j];
            if(b==a && c<2){
                c++;
                b=0;
                if(j==(A.length-1))
                    return false;
            }
        }
        if(c==2 && b==a)
            return true;
        else
            return false;


    }
}
``


 

Published 38 original articles · won praise 0 · Views 1135

Guess you like

Origin blog.csdn.net/weixin_45489155/article/details/104789694