問題描述
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]