1013. 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])

这道题,我没有做出来,看了discuss,作者rock写的想法感觉很好

1、检查总数是否能被3整除;
2、循环遍历数组A,计算和的一部分;如果找到平均值,则将该部分重置为0,并增加计数器;
3、到最后,如果平均可以看到至少3次,返回true;否则返回假。
注意:如果在数组结束前找到2次平均值(sum / 3),那么剩下的部分也等于平均值。因此,计数器达到3后无需继续。

public boolean canThreePartsEqualSum(int[] A) {
        int sum = Arrays.stream(A).sum(), part = 0, cnt = 0;
        if (sum % 3 != 0) { return false; }
        for (int a : A) {
            part += a;
            if (part != sum / 3) { continue; } // not the average: sum / 3
            if (++cnt == 3) { return true; } // find an average, increase the counter.
            part = 0; // reset part.
        }
        return false;
    }

猜你喜欢

转载自blog.csdn.net/maomao_dreamhigh/article/details/88934628