888. Fair Candy Swap

Posted whatyouthink

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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]

 

以上是关于888. Fair Candy Swap的主要内容,如果未能解决你的问题,请参考以下文章

888. 公平的糖果交换

AGC027 A - Candy Distribution Again

关于将 string::swap() 与临时对象一起使用的问题

#yyds干货盘点#CSS-ing Candy Ghost 按钮

codeforces 897A Scarborough Fair 暴力签到

决策树算法