题目内容
You are given two arrays A and B consisting of N integers each.
Index K is named fair if the four sums (A[0] +... + A[K-1]), (A[K] +... + A[N-1]), (B[0] +... + B[K-1]) and (B[K] + ... + B[N-1]) are all equal. In other words, K is the index where the two arrays, A and B, can be split (into two non-empty arrays each) in such a way that the sums of the resulting arrays’ elements are equal.
For example, given arrays A = [0, 4, -1, 0, 3] and B = [0, -2, 5, 0, 3], index K = 3 is fair.
The sums of the four subarrays are all equal: 0 + 4+ (-1) = 3; 0+3 = 3; 0+(-2)+5=3 and 0+3=3. On the other hand, index K = 2 is not fair, the sums of the Subarrays are: 0 + 4 = 4; (-1)+0+3=2: 0+(-2) =-2 and 5+0+3=8.
Write a function:
Class Solution { public int solution(int[] A, int[] B); }
which, given two arrays of integers A and B, returns the total number of fair indexes.
Examples:
1. Given A = [0, 4, -1, 0, 3] and B = (0, -2, 5, 0, 3], your function should return 2. The fair indexes are 3 and 4. In both cases, the sums of elements of the subarrays are equal to 3.
2. Given A = [2, -2, -3, 3] and B = (0, 0, 4, -4], your function should return 1. The only fair index is 2. Index 4 is not fair as the subarrays containing indexes from K to N - 1 would be empty.
3. Given A = [4, -1, 0, 3] and B = [-2, 6, 0, 4], your function should return 0. There are no fair indexes.
4. Given A = [3, 2, 6] and B = [4, 1, 6], your function should return 1.
5. Given A = [1, 4, 2, -2, 5], B =[7, -2, -2, 2, 5], your function should return 2. The fair indexes are 2 and 4.
解法一
思路
先求两个数组A和B每个的和,然后遍历数组A和B,分别求出数组A和数组B的左边的子数组和和右边的子数组的和。如果四个子数组的和都相同时候,fairCount加1.最后输出fairCount。
java 代码实现
public class Task3 {public int solution(int[] A, int[] B){int sumA = Arrays.stream(A).sum();int sumB = Arrays.stream(B).sum();int fairCount = 0;int leftSubArrayASum = 0;int leftSubArrayBSum = 0;for (int index=0; index< A.length-1 ; index++){leftSubArrayASum = leftSubArrayASum + A[index];leftSubArrayBSum = leftSubArrayBSum + B[index];if (index==0){//each subarrays would be non-emptycontinue;}if (leftSubArrayASum == leftSubArrayBSum && (sumA-leftSubArrayASum) ==(sumB-leftSubArrayBSum)){fairCount ++;}}return fairCount;}public static void main(String[] args) {Task3 task = new Task3();int[] A = new int[]{0, 4, -1, 0, 3};int[] B = new int[]{0, -2, 5, 0, 3};System.out.println(task.solution(A, B)); // Output: 2A = new int[]{2, -2, -3, 3};B = new int[]{0, 0, 4, -4};System.out.println(task.solution(A, B)); // Output: 1A = new int[]{4, -1, 0, 3};B = new int[]{-2, 6, 0, 4};System.out.println(task.solution(A, B)); // Output: 0A = new int[]{3, 2, 6};B = new int[]{4, 1, 6};System.out.println(task.solution(A, B)); // Output: 1A = new int[]{1, 4, 2, -2, 5};B = new int[]{7, -2, -2, 2, 5};System.out.println(task.solution(A, B)); // Output: 2}
}