问题描述
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]