LeetCode 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.

题目分析及思路

给定两组整数数组,分别代表两个人所拥有的糖果长度。要求经过一次交换后,两人所拥有的糖果长度相等。可以先将两人要交换的糖果长度分别设为x和y,然后求解。根据得到的结果遍历数组即可。

python代码

class Solution:

    def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:

        s_a, s_b = sum(A), sum(B)

        set_b = set(B)

        for x in A:

            if x + (s_b-s_a) // 2 in set_b:

                return [x, x+(s_b-s_a) // 2]

        

        

猜你喜欢

转载自www.cnblogs.com/yao1996/p/10521115.html
今日推荐