Alice and Bob have candy bars of different sizes:A[i]is the size of thei-th bar of candy that Alice has, andB[j]is the size of thej-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 arrayans whereans[0]is the size of the candy bar that Alice must exchange, andans[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.

思路:sumA - a + b = sumB - b + a

sumA - 2a = sumB - 2b

class Solution {
    public int[] fairCandySwap(int[] A, int[] B) {
        int sumA = 0;
        int sumB = 0;

        for(int a: A)
            sumA += a;
        for(int b: B)
            sumB += b;

        int[] res = new int[2];
        HashSet<Integer> set = new HashSet<Integer>();

        for(int a: A)
            set.add(sumA - a - a);

        for(int b: B) {
            if(set.contains(sumB - b - b)) {
                res[0] = (sumA - sumB + b + b) / 2;
                res[1] = b;
            }
        }

        return res;
    }
}

results matching ""

    No results matching ""