Leetcode学习笔记:#888. Fair Candy Swap

Leetcode学习笔记:#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.

实现:

public int[] fairCandySwap(int[] A, int[] B){
	int dir = (IntStream.of(A).sum() - IntStream.of(B).sum()) / 2;
	HashSet S = new HashSet<>();
	for(int a : A) S.add(a);
	for(int b : B)
		if(S.contains(d + dif)) 
			return new int[] {b + dif, b};
	return new int[0];
}

思路:
设dif为两数组之和除以2,则找到a = b+dif即可

你可能感兴趣的:(Leetcode)