888. Fair Candy Swap

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.

题目的意思是给出两个数组,两边交换一个数,是的两个数组和相等,保证一定有解。

需要寻找两个数,他们的差是两个数组和差的一半,为什么是一半,举个例子,sumA = 10 sumB=14 需要从A和B分别找一个数,他们差是2,然后交换,sumA=12,sumB=12.

class Solution(object):
    def fairCandySwap(self, A, B):
        """
        :type A: List[int]
        :type B: List[int]
        :rtype: List[int]
        """
        diff = (sum(A) - sum(B)) // 2
        s = set(A)
        for value in set(B):
            if value + diff in s:
                return [value + diff, value]
原文地址:https://www.cnblogs.com/whatyouthink/p/13223303.html