https://leetcode-cn.com/problems/fair-candy-swap/
爱丽丝和鲍勃有不同大小的糖果棒:
返回一个整数数组 ans,其中 ans[0] 是爱丽丝必须交换的糖果棒的大小,ans[1] 是 Bob 必须交换的糖果棒的大小。
如果有多个答案,你可以返回其中任何一个。
输入:A = [1,1], B = [2,2]
输出:[1,2]
输入:A = [1,2,5], B = [2,4]
输出:[5,4]
给两个数组,从两个数组中分别选取一个进行交换,使得交换后的数组和相等。
经典的两数和问题。
1. 两数之和 https://blog.csdn.net/IOT_victor/article/details/88196958
import collections
class Solution(object):
def fairCandySwap(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: List[int]
"""
sum_a = sum(A)
sum_b = sum(B)
diff = sum_b - sum_a
# hashmap = collections.Counter(A)
hashmap = set(A) # 去重
for b in B:
if b - diff//2 in hashmap:
return [b - diff//2, b]
A = [1, 1]
B = [2, 2]
s = Solution()
print(s.fairCandySwap(A, B))
时间复杂度:O(n+m),n 是序列 A 的长度,m 是序列 B 的长度
空间复杂度:O(n)