1. 程式人生 > >【python3】leetcode 888. Fair Candy Swap(easy)

【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