题目:判断某个数组是否可以等分,其中分割数组的某个元素不算在内。比如:{2,5,1,1,1,1,4,7,5,2,1,7}可以四等分成{2,5}{1,1,1,4}{5,2}{7}

public class HasEqualSubArray
{

public static int hasEqualSubArray(int[] input){
    //如果长度小于3则不存在等分
    if(null == input || input.length < 3){
        return -1;
    }
    
    int subSum = 0;//总和相等的字数组的总和大小
    //i作为分隔点,根据i前面的总和,判断i后面的所有字数组是否有相同的总和
    for(int i = 1; i < input.length-1; i++){
        subSum += input[i-1];

        int laterSum = 0;
        boolean hasEqualSum = true;
        for(int j = i+1; j < input.length; j++){
            laterSum = laterSum + input[j];
            if(laterSum < subSum){
                if(j == input.length-1){
                    hasEqualSum = false;
                }
                continue;
            }else if(laterSum == subSum){
                laterSum = 0;
                j++;
            }else{
                hasEqualSum = false;
                break;
            }
        }
        
        if(hasEqualSum){
            return subSum;
        }else if(i == input.length-2){
            return -1;
        }
    }
    return -1;
}

public static void main(String[] args)
{
    int[] case1 = new int[]{2,5,1,1,1,1,4,7,5,2,1,7};
    int[] case2 = new int[]{2,24,1};
    int[] case3 = new int[]{2,2,2,2,2,2,2};
    int[] case4 = new int[]{1,2,3,0,6,0,3,3};
    System.out.println(hasEqualSubArray(case1));
}

}

上一篇:android 摇一摇+震动+声音效果


下一篇:如何提高大型工程的编译速度?