leetcode解题之将数组分成和相等的三个部分

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/partition-array-into-three-parts-with-equal-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路一是根据题意数组要分成三等份,那么数组的和只能是3的倍数或者0,所以只要在A.length-2的范围内找到两个等于平均值就可以了

class Solution {
    public boolean canThreePartsEqualSum(int[] A) {
        int total=0;
        for(int i=0;i<A.length;i++){
            total+=A[i];
        }
        System.out.println(total);
        if(total%3!=0){
            return false;
        }
        int tem=0;
        List<Integer> list = new ArrayList();
        for(int i=0;i<A.length-1;i++){
            tem+=A[i];
            if(tem==total/3){
               list.add(tem);
                tem=0;
            }
        }
        if(list.size()>1){
            return true;
        }
        return false;
    }
}

思路二是从数组的两头开始找平均值,根据i+1<j来判定

class Solution {
    public boolean canThreePartsEqualSum(int[] A) {
        int total=0;
        for(int i=0;i<A.length;i++){
            total+=A[i];
        }
        if(total%3!=0){
            return false;
        }
        int avg = total/3;
        int i=0,j=A.length-1;
        int first=0,third=0;
        boolean res=false;
        for(;i+1<j;i++){
            first+=A[i];
            if(first==avg) break;
        }
        for(;j>i+1;j--){
            third+=A[j];
            if(third==avg) break;
        }
        return first==avg&&third==avg&&i+1<j;
    }
}
发布了98 篇原创文章 · 获赞 0 · 访问量 3989

猜你喜欢

转载自blog.csdn.net/l888c/article/details/104791357
今日推荐