888. Fair Candy Swap。

版权声明:本文为博主原创文章,转载请标明出处:http://blog.csdn.net/leafage_m https://blog.csdn.net/Leafage_M/article/details/85792710

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]

原文链接:https://leetcode.com/problems/fair-candy-swap/


文中的Alice 和 Bob分别有不同数量的糖果,数组A代表Alice拥有的糖果,其中索引 i 上的元素A[i]代表第 i 种糖果有多少个,B也是如此。现在需要让这两个人分别从各自的糖果中取出一种与对方交换,然后必须满足交换之后两个人糖果总数相等。


按照题意,交换之后每个人的糖果数目是一样的,所以我们可以先分别计算出之前每个人的糖果总和,并且相加除以2得到最后每个人应该拥有的数目。

在这里插入图片描述

然后用原来A拥有的糖果总数减去平均的数目,会得到一个差值diff,这个差值就是A与B进行交换之后需要抵消的差值。

在这里插入图片描述

然后开始遍历A种的所有糖果,当发现A种的某一类糖果数量(也就是某一个元素数值)减去这个差值diff之后恰好等于B种的某一类糖果数量 x - diff = y,也就是说交换x和y之后正好能够弥补掉这个差值diff。所以这里的x和y就是这两个人各自需要交换的糖果,也就是所求的最终答案。

在这里插入图片描述

class Solution {
public:
    vector<int> fairCandySwap(vector<int>& A, vector<int>& B) {
        vector<int> res;
        int Asum=accumulate(A.begin(),A.end(),0);//计算出AB的总和
        int Bsum=accumulate(B.begin(),B.end(),0);

        int diff = (Asum - Bsum)/2;//计算出A与平均值之间的差距是多少,等同于下面的运算
        //int diff = Asum - (Asum + Bsum)/2;

        for(int i : A) {
            if(find(B.begin(),B.end(),i-diff)!=B.end()) {
                res.push_back(i);
                res.push_back(i-diff);
                break;
            }
        }

        return res;
    }
};

利用set会快上很多。

class Solution {
public:
    vector<int> fairCandySwap(vector<int>& A, vector<int>& B) {
        int sum_A=0;
        int sum_B=0;
        for(int i=0;i<A.size();i++)
            sum_A += A[i];
        for(int j=0;j<B.size();j++)
            sum_B += B[j];
        int diff = (sum_A-sum_B)/2;
        unordered_set<int> hashset(B.begin(),B.end());
        for (int i =0;i<A.size();i++)
        {
            if ((A[i]-diff)>=1)
            {
                auto elem = hashset.find(A[i]-diff);
                if (elem != hashset.end())
                {
                    vector<int> result {A[i], *elem};
                    return result;
                }
            }
        }
    }
};

猜你喜欢

转载自blog.csdn.net/Leafage_M/article/details/85792710
今日推荐