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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/maotianyi941005/article/details/84994041

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

猜你喜欢

转载自blog.csdn.net/maotianyi941005/article/details/84994041
今日推荐