1. 程式人生 > >LeetCode-888.Fair Candy Swap 公平交換糖果(C++實現)

LeetCode-888.Fair Candy Swap 公平交換糖果(C++實現)

一、問題描述
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>

三、測試效果在這裡插入圖片描述
嗯不知道為何比較耗時,自我感覺程式編的還挺簡潔的賴。。。