题目

888. Fair Candy Swap

我的代码(效率低)

class Solution(object):
    def fairCandySwap(self, A, B):
        """
        :type A: List[int]
        :type B: List[int]
        :rtype: List[int]
        """
        dif =(sum(A)-sum(B))/2
        A=set(A)
        B=set(B)
        for i in A:
            if i-dif in B:
                return[i,i-dif]

优秀代码

使用排序+双指针可以大大提高运行速度。

class Solution(object):
    def fairCandySwap(self, A, B):
        """
        :type A: List[int]
        :type B: List[int]
        :rtype: List[int]
        """
        sumA, sumB = sum(A), sum(B)
        diff = (sumA - sumB) / 2
        A, B = sorted(A), sorted(B)
        i, j = 0, 0
        while True:
            if A[i] - B[j] == diff:
                return [A[i], B[j]]
            elif A[i] - B[j] < diff:
                i += 1
            else:
                j += 1

相关文章:

  • 2021-12-31
  • 2021-12-24
  • 2022-12-23
  • 2022-01-20
  • 2021-08-29
猜你喜欢
  • 2021-06-12
  • 2022-01-03
  • 2021-12-19
  • 2022-12-23
  • 2022-12-23
  • 2021-04-30
  • 2021-11-30
相关资源
相似解决方案