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 <= A.length <= 10000
1 <= B.length <= 10000
1 <= A[i] <= 100000
1 <= B[i] <= 100000
It is guaranteed that Alice and Bob have different total amounts of candy.
It is guaranteed there exists an answer.

这题分析起来费了一点时间,要让两人的糖果经过一次交换后数量相等,则先计算两者总糖果数量的差值,该值除以二就是两者需要交换的糖果的数量差值。思路都一样,但是我这里第一次的算法有点复杂了,通过两个索引去遍历直到找到正确的答案:

class Solution {
public:
    vector<int> fairCandySwap(vector<int>& A, vector<int>& B) {
        std::sort(A.begin(), A.end());
        std::sort(B.begin(), B.end());

        int sum_of_a = 0, sum_of_b = 0;
        for (auto v : A) {
            sum_of_a += v;
        }
        for (auto v : B) {
            sum_of_b += v;
        }
        int diff = (sum_of_a - sum_of_b) / 2;
        int cur_diff = 0;
        std::vector<int> res;
        res.reserve(2);
        int li = 0, ri = 0;

        while (diff != cur_diff) {
            cur_diff = A[li] - B[ri];
            if (cur_diff == diff) {
                break;
            }
            if (cur_diff < diff) {
                li++;
            } else {
                ri++;
            }
        }

        res.push_back(A[li]);
        res.push_back(B[ri]);
        return res;
    }
};

后来直接在另一个数组内查对应的值,发现速度也不是太快:

class Solution {
public:
    vector<int> fairCandySwap(vector<int>& A, vector<int>& B) {
        int sum_of_a = 0, sum_of_b = 0;
        unordered_set<int> others;

        for (auto v : A) {
            sum_of_a += v;
        }
        for (auto v : B) {
            sum_of_b += v;
            others.insert(v);
        }
        int diff = (sum_of_a - sum_of_b) / 2;
        for (auto v : A) {
            int other = v - diff;
            if (others.count(other) != 0) {
                return std::vector<int>{v, v - diff};
            }
        }
        return std::vector<int>{};
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day