爱丽丝和鲍勃有不同大小的糖果棒: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 <= 100001 <= B.length <= 100001 <= A[i] <= 1000001 <= B[i] <= 100000执行用时 :1224 ms, 在所有 cpp 提交中击败了14.22%的用户
内存消耗 :12 MB, 在所有 cpp 提交中击败了95.49%的用户
vector<int> fairCandySwap(vector<int>& A, vector<int>& B) {
int sumA=0, sumB=0;
for (auto& a : A) {
sumA += a;
}
for (auto& b : B) {
sumB += b;
}
int temp = sumA - sumB > 0 ? sumA - sumB : sumB - sumA;
temp = temp / 2;
for (auto& a : A) {
for (auto& b : B) {
if (a - b == temp || b - a == temp)
{
if(sumA - a + b == sumB - b + a)
return { a,b };
}
}
}
return { 0,0 };
}执行用时 :132 ms, 在所有 cpp 提交中击败了88.39%的用户
内存消耗 :12.2 MB, 在所有 cpp 提交中击败了83.46%的用户
vector<int> fairCandySwap(vector<int>& A, vector<int>& B) {
int sumA=0, sumB=0;
for (auto& a : A) {
sumA += a;
}
for (auto& b : B) {
sumB += b;
}
int b=0,temp = sumA - sumB > 0 ? sumA - sumB : sumB - sumA;
temp = temp / 2;
sort(A.begin(), A.end());
sort(B.begin(), B.end());
for (auto& a : A) {
if (lower_bound(B.begin(),B.end(),a + temp)!=B.end())
{
b = *(lower_bound(B.begin(), B.end(), a + temp));
if(sumA - a + b == sumB - b + a)
return { a,b };
}
if (lower_bound(B.begin(), B.end(), a - temp) != B.end())
{
b = *(lower_bound(B.begin(), B.end(), a - temp));
if (sumA - a + b == sumB - b + a)
return { a,b };
}
}
return { 0,0 };
}