# 888.Fair Candy Swap

**888.Fair Candy Swap**

难度:Easy

> 爱丽丝和鲍勃有不同大小的糖果棒：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 <= 10000
1 <= B.length <= 10000
1 <= A[i] <= 100000
1 <= B[i] <= 100000
保证爱丽丝与鲍勃的糖果总量不同。
答案肯定存在。
```

求出两数之差，然后判断A中的加上这个差的数在B中是否存在。可以借助集合。

```
class Solution {
public:
    vector<int> fairCandySwap(vector<int>& A, vector<int>& B) {
        unordered_set<int> tmp(B.begin(), B.end());
        int sa= accumulate(A.begin(), A.end(),0);
        int sb= accumulate(B.begin(),B.end(),0);
        vector<int >res={0,0};
        if(sa>sb)
        {
            int r=(sa-sb)/2;
            for(auto i : A)
            {
                if(tmp.count(i-r))
                {
                    res[0]=i;
                    res[1]=i-r;
                    return res;
                }
            }
        }
        else
        {
            int r=(sb-sa)/2;
            for(auto i : A)
            {
                if(tmp.count(i+r))
                {
                    res[0]=i;
                    res[1]=i+r;
                    return res;
                }
            }
        }
        
         return res;
    }
};
```

> 执行用时 :216ms, 在所有 C++ 提交中击败了64.36%的用户\
> 内存消耗 :19.9MB, 在所有 C++ 提交中击败了32.33%的用户


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/888.fair_candy_swap.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
