【LeetCode】888. Fair Candy Swap 解题报告(Python)

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

【LeetCode】888. Fair Candy Swap 解题报告(Python)

标签(空格分隔): LeetCode

作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/fair-candy-swap/description/

题目描述:

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.

Example 1:

Input: A = [1,1], B = [2,2]
Output: [1,2]

Example 2:

Input: A = [1,2], B = [2,3]
Output: [1,2]

Example 3:

Input: A = [2], B = [1,3]
Output: [2,3]

Example 4:

Input: A = [1,2,5], B = [2,4]
Output: [5,4]

Note:

  1. 1 <= A.length <= 10000
  2. 1 <= B.length <= 10000
  3. 1 <= A[i] <= 100000
  4. 1 <= B[i] <= 100000
  5. It is guaranteed that Alice and Bob have different total amounts of candy.
  6. It is guaranteed there exists an answer.

题目大意

交换A,B两个数组中的一个数字,使得两个数组的和相等。要返回的结果是个要交换的两个数字,分别来自A,B。

解题方法

看了一眼A,B数组的范围就知道,时间复杂度一定不能太高。我们分析一下可以看出,交换之后A,B数组的和都应该是相同的,也就是两个数组和的平均数。

所以对数组A进行遍历,那么对于每个数字,得到除去该数值以外其他数字的和;使用平均数减去这个和,看这个结果是否在数组B中,如果在返回即可。

也就是说,通过上面的方法,我们使得数组A的和等于平均数,这种情况下,数组B的和也为平均数。

代码如下:

class Solution(object):
    def fairCandySwap(self, A, B):
        """
        :type A: List[int]
        :type B: List[int]
        :rtype: List[int]
        """
        sum_A, sum_B, set_B = sum(A), sum(B), set(B)
        target = (sum_A + sum_B) / 2
        for a in A:
            b = target - (sum_A - a)
            if b >= 1 and b <= 100000 and b in set_B:
                return [a, b]

参考资料:无

日期

2018 年 8 月 24 日 ———— Keep fighting!

猜你喜欢

转载自blog.csdn.net/fuxuemingzhu/article/details/82013077
今日推荐