Leetcode - 888 Fair Candy Swap (Easy)
题目描述:两个人分别有数组 A 与数组 B 块糖,让他们两个交换一块糖使得交换后两人拥有的糖数相同,即 A、B 两数组数组和相同。
Input: A = [1,1], B = [2,2]
Output: [1,2]
解题思路:公式求解,sum(A) - x + y = sum(B) - y + x => y = x + (sum(A) - sum(B)) / 2。
public int[] fairCandySwap(int[] A, int[] B) {
int sa = 0, sb = 0;
for (int x : A) sa += x;
for (int x : B) sb += x;
int delta = (sb - sa) / 2;
Set<Integer> set = new HashSet<>();
for (int x : B) set.add(x);
for (int x : A) {
if (set.contains(x + delta)) {
return new int[]{x, x + delta};
}
}
return null;
}