Question:
Alice and Bob have candy bars of different sizes: A[i]
is the size of the i
-th bar of candy that Alice has, and B[j]
is the size of the j
-th bar of candy that Bob has.
Since they are friends, they would like to exchange one candy bar each so that after the exchange, they both have the same total amount of candy. (The total amount of candy a person has is the sum of the sizes of candy bars they have.)
Return an integer array ans
where ans[0]
is the size of the candy bar that Alice must exchange, and ans[1]
is the size of the candy bar that Bob must exchange.
If there are multiple answers, you may return any one of them. It is guaranteed an answer exists.
爱丽丝和鲍勃的糖果棒大小不同:A[i]是爱丽丝拥有的第i条糖果的大小,B[j]是鲍勃拥有的第j条糖果的大小。
既然他们是朋友,他们想每人交换一根糖果,这样在交换之后,他们俩的糖果总数是一样的。(一个人所拥有的糖果总数是他们所拥有的糖果棒大小的总和。)
返回一个整数数组ans,其中ans[0]是Alice必须交换的糖果条的大小,ans[1]是Bob必须交换的糖果条的大小。
Example:
Input: A = [1,1], B = [2,2]
Output: [1,2]
Input: A = [1,2], B = [2,3]
Output: [1,2]
Input: A = [2], B = [1,3]
Output: [2,3]
Input: A = [1,2,5], B = [2,4]
Output: [5,4]
Solution:
/**
* @param {number[]} A
* @param {number[]} B
* @return {number[]}
*/
var fairCandySwap = function(A, B) {
let res;
let sumA = A.reduce((a,b)=>a+b);
let sumB = B.reduce((a,b)=>a+b);
let mid = (sumA+sumB)/2;
for (let i=0; i<A.length; i++) {
let l = sumA - A[i];
let need = mid - l ;
let s = B.indexOf(need);
if (s>-1 && sumB-B[s]+A[i] ===mid) {
res = [A[i],B[s]];
break;
}
}
return res
};