题目地址:
https://leetcode.com/problems/fair-candy-swap/
给定两个数组 A A A和 B B B,要求将 B B B中某个数和 A A A中某个数交换,使得交换后两个数组的和相等,返回 A A A中和 B B B中交换的两个数。题目保证解存在,返回任意一种解即可。
设 A A A交换的是 x x x, B B B交换的是 y y y,则有 S A − x + y = S B − y + x S_A-x+y=S_B-y+x SA−x+y=SB−y+x,所以 y = x + S B − S A 2 y=x+\frac{S_B-S_A}{2} y=x+2SB−SA,可以用哈希表存下 B B B中的数,然后遍历 A A A中每个 x x x,看哈希表中是否存在 x + S B − S A 2 x+\frac{S_B-S_A}{2} x+2SB−SA。代码如下:
import java.util.HashSet;
import java.util.Set;
public class Solution {
public int[] fairCandySwap(int[] aliceSizes, int[] bobSizes) {
int sumA = 0, sumB = 0;
for (int x : aliceSizes) {
sumA += x;
}
Set<Integer> setB = new HashSet<>();
for (int x : bobSizes) {
sumB += x;
setB.add(x);
}
for (int x : aliceSizes) {
if (setB.contains(x + (sumB - sumA >> 1))) {
return new int[]{x, x + (sumB - sumA >> 1)};
}
}
return null;
}
}
时空复杂度 O ( max { l A , l B } ) O(\max\{l_A,l_B\}) O(max{lA,lB})。