【python3】leetcode 888. Fair Candy Swap(easy)

888. Fair Candy Swap(easy)

 

ALice要给bob一堆糖果,bob要给alice一堆,最后两人糖果总数要相同,假设alice给的那堆有a个,bob给的那堆有b个

解方程吧~~ sum(A)-a+b = sum(b) - b + a

         ->            b = a + (sum(A) + sum(B)) / 2  = a + x 

所以遍历A查找如果给A[i],那么找 A[i] + x在不在B中

如果不用set会超时,因为A B corner case都挺大的

class Solution:
    def fairCandySwap(self, A, B):
        """
        :type A: List[int]
        :type B: List[int]
        :rtype: List[int]
        """
        x = int((sum(B) - sum(A))/2)
        A = set(A)
        B = set(B)
        for a in A:
            if((a+x) in B):
                return [a,a+x]

Runtime: 128 ms, faster than 23.60% of Python3

你可能感兴趣的:(python,leetcode)