LeetCode(easy)-888. Fair Candy Swap

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/f823154/article/details/82954558

888. Fair Candy Swap
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]
题目:
爱丽丝和鲍勃有不同大小的糖果棒:A [i]是爱丽丝拥有的第i个糖果棒的大小,而B [j]是鲍勃拥有的第j个糖果棒的大小。由于他们是朋友,他们想交换一个糖果,以便交换后,他们都有相同的糖果总量。(一个人拥有的糖果总量
是他们拥有的糖果大小的总和)返回一个整数数组ans,其中ans [0]是Alice必须交换的糖果的大小,ans [1]是Bob必须交换的糖果的大小。如果有多个答案,您可以返回其中任何一个。 保证答案存在。
解法一:

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* fairCandySwap(int* A, int ASize, int* B, int BSize, int* returnSize) {
    int sum_a=0;
	int sum_b=0;
    int i = 0;
	int j = 0;
	int k,z;
    *returnSize = 2;
	int* tmp=(int*)malloc(2*sizeof(int));     //用于存储交换的糖果大小 
	while(i<ASize){
		sum_a +=A[i];
		i++;
	}
	while(j < BSize){
	    sum_b += B[j];
	    j++;
	} 
	for(k=0;k < ASize;k++){
		for(z=0;z < BSize;z++){
			if((sum_a + B[z] - A[k]) == (sum_b - B[z] + A[k])){
				tmp[0]=	A[k];
		        tmp[1]= B[z];
			}
		}
	}
	return tmp;
}

Runtime: 1452 ms

猜你喜欢

转载自blog.csdn.net/f823154/article/details/82954558
今日推荐