888.公平交换糖果棒

爱丽丝和鲍勃有不同大小的糖果棒:A[i] 是爱丽丝拥有的第 i 根糖果棒的大小,B[j] 是鲍勃拥有的第 j 根糖果棒的大小。
因为他们是朋友,所以他们想交换一根糖果棒,这样交换后,他们都有相同的糖果总量。(一个人拥有的糖果总量是他们拥有的糖果棒大小的总和。)
返回一个整数数组 ans,其中 ans[0] 是爱丽丝必须交换的糖果棒的大小,ans[1] 是 Bob 必须交换的糖果棒的大小。
如果有多个答案,你可以返回其中任何一个。保证答案存在。

/** 1.HashSet ,先将A放入set中  
 *  2.要求返回[x,y]x为A换到B中,y反之
 *  3.根据条件 ,两人交换后糖果总量相等,设A为totalA,B为totalB
 *  4.则 totalA-x+y = totalB-y+x; ==> x=(totalA-totalB)/2+y;
 *  5.遍历B ,是否set中存在使得4中条件成立的x
 */
class Solution {
    public int[] fairCandySwap(int[] A, int[] B) {
        int totalA = Arrays.stream(A).sum();
        int totalB = Arrays.stream(B).sum();
        int target = (totalA-totalB)/2;
        int res[] = new int[2];

        Set<Integer> set = new HashSet<>();

        for(int i=0;i<A.length;i++){
            set.add(A[i]);
        }

        for(int y : B){
            int x = target + y;
            if(set.contains(x)){
                res[0] = x;
                res[1] = y;
                break;
            }
        }

        return res;
    }
}
posted @ 2021-02-01 09:40  _zjk  阅读(67)  评论(0)    收藏  举报