Fair Candy Swap
给两个整数组, 交换一对整数, 让两个整数组想加的和相等. 首先先求两个数组的和, 然后求他们的差, 这个差值就是交换两个数的差值.
class Solution {
public int[] fairCandySwap(int[] A, int[] B) {
int sumA = 0;
int sumB = 0;
for(int a : A)
sumA += a;
for(int b : B)
sumB += b;
int diff = (sumB - sumA) / 2;
Set<Integer> set = new HashSet<Integer>();
for(int i = 0 ; i < B.length; i++) {
set.add(B[i]);
}
for(int a : A) {
if(set.contains(a+diff))
return new int[]{a, a+diff};
}
return null;
}
}