Description:
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]
本题要求交换两个数组中的某个元素,使得交换后的两个数组元素之和相等。
思路一:采用暴力解法,依次遍历两个数组,判断是否满足题意。
思路二:采用网友 lee215 的思路,使用 unordered_set 结构查找时间为常数,方法为:先求出 diff = (sum(A) - sum(B)) / 2,再返回(a,b)其中 a = b + diff。
C++ 代码(思路一)
class Solution {
public:
vector<int> fairCandySwap(vector<int>& A, vector<int>& B) {
int sumA = 0, sumB = 0;
for(int a : A) sumA += a;
for(int b : B) sumB += b;
for(size_t i = 0; i < A.size(); ++i)
{
for(size_t j = 0; j < B.size(); ++j)
{
if(sumA + B[j] - A[i] == sumB + A[i] - B[j])
{
return {A[i], B[j]};
}
}
}
return {-1, -1};
}
};
运行时间:956ms
运行内存:12.2M
C++ 代码(思路二)
class Solution {
public:
vector<int> fairCandySwap(vector<int>& A, vector<int>& B) {
int dif = (accumulate(A.begin(), A.end(), 0) - accumulate(B.begin(), B.end(), 0)) / 2;
std::unordered_set<int> s(A.begin(), A.end());
for (int b: B)
if (s.count(b + dif))
return {b + dif, b};
return {-1,-1};
}
};
运行时间:120ms
运行内存:21.1M
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于