Equi3(Codality)
题目:A non-empty zero-indexed array A consisting of N positve integers is given. A pair of indices (P, Q), such that 0 <= P <= Q < N, is called a slice of array A. The sum of a slice (P, Q) is the total of A[P] + A[P+1] + ... + A[Q].
The equi-3 pair is a pair of indices (X, Y), such that 0 < X, X+1 < Y < N-1, and the sums of slices (0, X-1), (X+1, Y-1), (Y+1, N-1) are all equal.
That, given a non-empty zero-indexed array A consisting of N integers, returns 1 if array A contains an equi-3 pair and 0 otherwise.
Output Format:
Print equi pair in first line in the format { a,b } Print slices in the format { 0,a-1 },{ a+1,b-1 }, { b+1,N-1 }
OR
Print "Array does not contain any equi pair" if there are no equi pairs in the array
public class Equi3 {
public int solution(int[] A) {
int sum = 0, leftSum = 0, midSum = 0, rightSum = 0;
int n = A.length;
int[] totals = new int[n];
for (int i=0; i<n; i++) {
sum += A[i];
totals[i] = sum;
}
int left = 1, right = n - 2;
while (left+1 < right) {
leftSum = totals[left-1];
midSum = totals[right-1] - totals[left];
rightSum = totals[n-1] - totals[right];
if ((leftSum == midSum) && (midSum == rightSum)) {
System.out.println("left slice =" + left +",right slice="+right);
return 1;
} else if (leftSum > rightSum) {
right--;
} else if (leftSum < rightSum){
left++;
} else {
left++;
right--;
}
}
return 0;
}
public static void main(String[] args) {
//int[] in = {4,5,1,1,1,1,4,3,1};//left slice =1,right slice=6
//int[] in = {8,3,5,2,10,6,7,9,5,2};//left slice =3,right slice=6
int[] in = {6,2,6,2,3,3,1,9};//Array does not contain any equi pair
Equi3 instance = new Equi3();
System.out.println(instance.solution(in));
}
}