爱丽丝和鲍勃有不同大小的糖果棒:A[i]
是爱丽丝拥有的第 i
根糖果棒的大小,B[j]
是鲍勃拥有的第 j
根糖果棒的大小。
因为他们是朋友,所以他们想交换一根糖果棒,这样交换后,他们都有相同的糖果总量。(一个人拥有的糖果总量是他们拥有的糖果棒大小的总和。)
返回一个整数数组 ans
,其中 ans[0]
是爱丽丝必须交换的糖果棒的大小,ans[1]
是 Bob 必须交换的糖果棒的大小。
如果有多个答案,你可以返回其中任何一个。保证答案存在。
示例 1:
输入:A = [1,1], B = [2,2] 输出:[1,2]
示例 2:
输入:A = [1,2], B = [2,3] 输出:[1,2]
示例 3:
输入:A = [2], B = [1,3] 输出:[2,3]
示例 4:
输入:A = [1,2,5], B = [2,4] 输出:[5,4]
提示:
1 <= A.length <= 10000
1 <= B.length <= 10000
1 <= A[i] <= 100000
1 <= B[i] <= 100000
- 保证爱丽丝与鲍勃的糖果总量不同。
- 答案肯定存在。
哈希表实现。
class Solution:
def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:
diff = (sum(aliceSizes) - sum(bobSizes)) >> 1
s = set(bobSizes)
for a in aliceSizes:
target = a - diff
if target in s:
return [a, target]
class Solution {
public int[] fairCandySwap(int[] aliceSizes, int[] bobSizes) {
int s1 = 0, s2 = 0;
Set<Integer> s = new HashSet<>();
for (int a : aliceSizes) {
s1 += a;
}
for (int b : bobSizes) {
s.add(b);
s2 += b;
}
int diff = (s1 - s2) >> 1;
for (int a : aliceSizes) {
int target = a - diff;
if (s.contains(target)) {
return new int[]{a, target};
}
}
return null;
}
}
function fairCandySwap(aliceSizes: number[], bobSizes: number[]): number[] {
let s1 = aliceSizes.reduce((a, c) => a + c, 0);
let s2 = bobSizes.reduce((a, c) => a + c, 0);
let diff = (s1 - s2) >> 1;
for (let num of aliceSizes) {
let target = num - diff;
if (bobSizes.includes(target)) {
return [num, target];
}
}
};
class Solution {
public:
vector<int> fairCandySwap(vector<int>& aliceSizes, vector<int>& bobSizes) {
int s1 = accumulate(aliceSizes.begin(), aliceSizes.end(), 0);
int s2 = accumulate(bobSizes.begin(), bobSizes.end(), 0);
int diff = (s1 - s2) >> 1;
unordered_set<int> s(bobSizes.begin(), bobSizes.end());
vector<int> ans;
for (int& a : aliceSizes) {
int target = a - diff;
if (s.count(target)) {
ans = vector<int>{a, target};
break;
}
}
return ans;
}
};