给定两个整数数组,请交换一对数值(每个数组中取一个数值),使得两个数组所有元素的和相等。
返回一个数组,第一个元素是第一个数组中要交换的元素,第二个元素是第二个数组中要交换的元素。若有多个答案,返回任意一个均可。若无满足条件的数值,返回空数组。
示例:
输入: array1 = [4, 1, 2, 1, 1, 2], array2 = [3, 6, 3, 3]
输出: [1, 3]
示例:
输入: array1 = [1, 2, 3], array2 = [4, 5, 6]
输出: []
提示:
1 <= array1.length, array2.length <= 100000
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int[] findSwapValues(int[] array1, int[] array2) {
int sum1 = 0;
for (int a : array1) {
sum1 += a;
}
int sum2 = 0;
Set<Integer> array2Set = new HashSet<>();
for (int a : array2) {
sum2 += a;
array2Set.add(a);
}
int sub = sum1 - sum2;
if (sub % 2 != 0) {
return new int[0];
}
for (int i = 0; i < array1.length; i++) {
int target = array1[i] - sub / 2;
if (array2Set.contains(target)) {
int[] result = new int[2];
result[0] = array1[i];
result[1] = target;
return result;
}
}
return new int[0];
}
}
//leetcode submit region end(Prohibit modification and deletion)