一、问题描述
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.
Example 1:
Input: A = [1,1], B = [2,2]
Output: [1,2]
Example 2:
Input: A = [1,2], B = [2,3]
Output: [1,2]
Example 3:
Input: A = [2], B = [1,3]
Output: [2,3]
Example 4:
Input: A = [1,2,5], B = [2,4]
Output: [5,4]
Note:
(1)1 <= A.length <= 10000
(2)1 <= B.length <= 10000
(3)1 <= A[i] <= 100000
(4)1 <= B[i] <= 100000
(5)It is guaranteed that Alice and Bob have different total amounts of candy.
(6)It is guaranteed there exists an answer.
题目要求:
爱丽丝和鲍勃的糖果棒大小不同:A[i]是爱丽丝拥有的第i条糖果的大小,B[j]是鲍勃拥有的第j条糖果的大小。
现在每人交换一根糖果,交换之后保证他们俩的糖果总数是一样的。(一个人的糖果总量是他们所拥有的糖果大小的总和。)
编写一个函数,返回值为整数数组ans,其中ans[0]是Alice必须交换的糖果条的大小,ans[1]是Bob必须交换的糖果条的大小。
如果有多个答案,你可以返回其中任何一个。保证答案是存在的。
二、思路及代码
思路:
既然是公平交换,则意味着交换之后,A中的糖果总数等于B中的糖果总数。总结规律可发现,只要满足由“(A中的糖果总数+B中的糖果总数)/2-A中的糖果总数+A[i]”式子算出的值n是B中的元素即可,最后将元素A[i]和n存放到数组fairswap中作为返回值。
代码:
vector<int> fairCandySwap(vector<int>& A, vector<int>& B)
{vector<int>fairswap;int sum1 = accumulate(A.begin(), A.end(),0);int sum2 = accumulate(B.begin(), B.end(), 0);for (int i = 0; i < A.size(); i++){int n = (sum1 + sum2) / 2 - sum1 + A[i];vector<int>::iterator f=find(B.begin(), B.end(), n);int index = f - B.begin();if (index >= 0 && index < B.size()){fairswap.push_back(A[i]);fairswap.push_back(n);return fairswap;}}
}
注意:
代码中accumulate()函数的功能为计算数组的元素之和,使用该函数需要添加如下头文件:
#include <numeric>
三、测试效果
嗯不知道为何比较耗时,自我感觉程序编的还挺简洁的赖。。。