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:

  1. Input: A = [1,1], B = [2,2]
  2. Output: [1,2]
  3. Input: A = [1,2], B = [2,3]
  4. Output: [1,2]
  5. Input: A = [2], B = [1,3]
  6. Output: [2,3]
  7. Input: A = [1,2,5], B = [2,4]
  8. Output: [5,4]

Solution:

  1. /**
  2. * @param {number[]} A
  3. * @param {number[]} B
  4. * @return {number[]}
  5. */
  6. var fairCandySwap = function(A, B) {
  7. let res;
  8. let sumA = A.reduce((a,b)=>a+b);
  9. let sumB = B.reduce((a,b)=>a+b);
  10. let mid = (sumA+sumB)/2;
  11. for (let i=0; i<A.length; i++) {
  12. let l = sumA - A[i];
  13. let need = mid - l ;
  14. let s = B.indexOf(need);
  15. if (s>-1 && sumB-B[s]+A[i] ===mid) {
  16. res = [A[i],B[s]];
  17. break;
  18. }
  19. }
  20. return res
  21. };