classSolution { publicint[] fairCandySwap(int[] aliceSizes, int[] bobSizes) { intsumA= Arrays.stream(aliceSizes).sum(); intsumB= Arrays.stream(bobSizes).sum(); intdelta= (sumA - sumB) / 2; Set<Integer> rec = newHashSet<Integer>(); for (int num : aliceSizes) { rec.add(num); } int[] ans = newint[2]; for (int y : bobSizes) { intx= y + delta; if (rec.contains(x)) { ans[0] = x; ans[1] = y; break; } } return ans; } }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
var fairCandySwap = function(aliceSizes, bobSizes) { const sumA = _.sum(aliceSizes), sumB = _.sum(bobSizes); const delta = Math.floor((sumA - sumB) / 2); const rec = newSet(aliceSizes); var ans; for (const y of bobSizes) { const x = y + delta; if (rec.has(x)) { ans = [x, y]; break; } } return ans; };
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: deffairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]: sumA, sumB = sum(aliceSizes), sum(bobSizes) delta = (sumA - sumB) // 2 rec = set(aliceSizes) ans = None for y in bobSizes: x = y + delta if x in rec: ans = [x, y] break return ans
funcfairCandySwap(aliceSizes []int, bobSizes []int) []int { sumA := 0 setA := map[int]struct{}{} for _, v := range aliceSizes { sumA += v setA[v] = struct{}{} } sumB := 0 for _, v := range bobSizes { sumB += v } delta := (sumA - sumB) / 2 for i := 0; ; i++ { y := bobSizes[i] x := y + delta if _, has := setA[x]; has { return []int{x, y} } } }