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.

思路

  • 如果用double for loop,时间复杂度会超过限制
  • 先求出A和B之间的差别的一半,diff
  • 不需要考虑重复的element,所以可以把A变成set
  • 循环B中的元素b,如果b+diff在A中,说明把这个元素加进B,能把B凑成总和一半
    def fairCandySwap(self, A, B):
        """
        :type A: List[int]
        :type B: List[int]
        :rtype: List[int]
        """
        diff = (sum(A) - sum(B)) // 2
        A = set(A)
        for b in B:
            if diff + b in A:
                return [b+diff, b]   
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,499评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,131评论 0 23
  • 无聊打算继续之前的爬虫工作 简单介绍基本的原理 浏览器驱动(chrome、PhantomJS) 浏览器自动化插件(...
    silentsvv阅读 1,479评论 0 4
  • 你说世界很大,我的世界却很小,小到只容得下你。你说要活得有气量,我却很小气,小气到只有我可以欺负你。 5长长的...
    慶三阅读 297评论 0 2
  • 林凡 你还好吗 你还记得我吗 你还是独自一个人喝酒吗 你还是一个人吃饭吗 你还是一个人抽烟吗 你还是一个人做噩梦吗...
    天赐欧尼酱阅读 153评论 0 1