888.公允的糖果交易(javascript)888.FairCandySwap

原创
小哥 3年前 (2022-11-10) 阅读数 6 #大杂烩

爱丽丝和鲍勃的糖果总量不同。给你两个数组 aliceSizes 和 bobSizes ,aliceSizes[i] 是爱丽丝拥有第一个 i 盒子里的糖果数量,bobSizes[j] 是鲍勃拥有第一个 j 糖果盒中的糖果数量。

两个人想互相交换一盒糖果,这样交换之后,他们可以拥有相同的糖果总数。一个人的糖果总数是他们每盒糖果的总数。

返回整数数组 answer,其中 answer[0] 是爱丽丝必须交换的糖果盒中的糖果数量,answer[1] 是鲍勃必须交换的糖果盒中的糖果数量。如果有多个答案,您可以返回它们。 任何一个 主题测试用例确保有对应于输入的答案。

Alice and Bob have a different total number of candies. You are given two integer arrays aliceSizes and bobSizes where aliceSizes[i] is the number of candies of the ith box of candy that Alice has and bobSizes[j] is the number of candies of the jth box of candy that Bob has.

Since they are friends, they would like to exchange one candy box 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 number of candies in each box they have.

Return an integer array answer where answer[0] is the number of candies in the box that Alice must exchange, and answer[1] is the number of candies in the box that Bob must exchange. If there are multiple answers, you may return any one of them. It is guaranteed that at least one answer exists.

示例 1:

输入:aliceSizes = [1,1], bobSizes = [2,2]
输出:[1,2]

示例 2:

输入:aliceSizes = [1,2], bobSizes = [2,3]
输出:[1,2]

示例 3:

输入:aliceSizes = [2], bobSizes = [1,3]
输出:[2,3]

示例 4:

输入:aliceSizes = [1,2,5], bobSizes = [2,4]
输出:[5,4]

提示:

  • 1 <= aliceSizes.length, bobSizes.length <= 104
  • 1 <= aliceSizes[i], bobSizes[j] <= 105
  • 爱丽丝和鲍勃的糖果总量不同。
  • 主题数据确保给定输入至少有一个有效答案。

解题思路
记住爱丽丝的糖果条的总尺寸是 sumA,鲍勃的糖果条的总尺寸是 sumB.设置答案{x,y}爱丽丝的尺码是 x 糖果条和鲍勃的大小是 y 糖果条交换,有以下等式:

sumA−x+y=sumB+x−y

化简:

x=(sumA-sumB)/2+y

(sumA-sumB)/2是一个固定的数字

将aliceSizes 哈希表中的数字被存储以快速找到对应的值。

通过遍历bobSizes阵列的每个项目(当它出现时)。 x=(sumA-sumB)/2+y 同时在aliceSizes在数组中,如果满足条件,可以返回它。

var fairCandySwap = function(aliceSizes, bobSizes) {
    let sumA=sum(aliceSizes),sumB=sum(bobSizes);
    let delta=Math.floor((sumA-sumB)/2);
    let newSet=new Set(aliceSizes)
    let answer=[]
    for(let i of bobSizes){
       let x= delta+ i
       if(newSet.has(x)){
           answer=[x,i]
           break;
       }
    }
    return answer
};
const sum = (arr) =>  {
  return arr.reduce(function(acr, cur){
    return acr + cur;
  });
}

三、ES6合集之Map和Set

leetcode: https://leetcode-cn.com/problems/fair-candy-swap/

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除