g0801_0900.s0888_fair_candy_swap.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0801_0900.s0888_fair_candy_swap;
// #Easy #Array #Hash_Table #Sorting #Binary_Search
// #2022_03_28_Time_18_ms_(68.20%)_Space_72.2_MB_(19.02%)
import java.util.HashSet;
public class Solution {
public int[] fairCandySwap(int[] aliceSizes, int[] bobSizes) {
int aSum = 0;
int bSum = 0;
int diff;
int[] ans = new int[2];
for (int bar : aliceSizes) {
aSum += bar;
}
for (int bar : bobSizes) {
bSum += bar;
}
diff = aSum - bSum;
HashSet set = new HashSet<>();
for (int bar : aliceSizes) {
set.add(bar);
}
for (int bar : bobSizes) {
if (set.contains(bar + diff / 2)) {
ans[0] = bar + diff / 2;
ans[1] = bar;
break;
}
}
return ans;
}
}