题目
我的代码(效率低)
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