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
  • 循環(huán)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]   
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,847評論 0 10
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,081評論 0 23
  • 無聊打算繼續(xù)之前的爬蟲工作 簡單介紹基本的原理 瀏覽器驅動(chrome、PhantomJS) 瀏覽器自動化插件(...
    silentsvv閱讀 1,516評論 0 4
  • 你說世界很大,我的世界卻很小,小到只容得下你。你說要活得有氣量,我卻很小氣,小氣到只有我可以欺負你。 5長長的...
    慶三閱讀 349評論 0 2
  • 林凡 你還好嗎 你還記得我嗎 你還是獨自一個人喝酒嗎 你還是一個人吃飯嗎 你還是一個人抽煙嗎 你還是一個人做噩夢嗎...
    天賜歐尼醬閱讀 163評論 0 1

友情鏈接更多精彩內容