888. Fair Candy Swap@python

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.

原题地址: Fair Candy Swap

题意: 给两个数组A B,各选取一个数进行交换,使得数组A的和等于数组B的和,返回交换的两个数

例子:

Input: A = [1,1], B = [2,2]
Output: [1,2]   # 交换之后 A = [1,2] B = [1, 2] 

(1)求出两个数组的平均值,也就是最后两个数组的和

(2)遍历数组A,假设当前值是要交换的数A[i],那么数组B中要交换的数是 平均值 - (sum(A) - A[i]) , 并判断此数是否在数组B中.如果存在,返回这两个数

注意: 可能存在重复值,是否存在重复值对结果没有影响,为了减少遍历次数,可以用 set() 去重,并且获取元素的时间复杂度是O(1)

代码:

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

时间复杂度:O(n)

遍历数组A为n次,判断一个数是否在set(B)中,需要1次,

空间复杂度:list转化为set,为O(n)

 

posted @ 2018-09-29 11:23  静静地挖坑  阅读(126)  评论(0)    收藏  举报