Leetcode Note: Go - Fair Candy Swap

Fair Candy Swap - LeetCode
https://leetcode.com/problems/fair-candy-swap/

  • Go 言語で取り組んだメモ

所感

  • int 配列 aliceSizes, bobSizez でキャンディ配分が渡されるので、これをフェアな数値に算出して int 配列で return する

回答

Fair Candy Swap - LeetCode
https://leetcode.com/problems/fair-candy-swap/solution/

golang map solution 100% - LeetCode Discuss
https://leetcode.com/problems/fair-candy-swap/discuss/1391545/golang-map-solution-100

func fairCandySwap(aliceSizes []int, bobSizes []int) []int {
	aliceSum := 0
	aliceBoxes := make(map[int]struct{}, len(aliceSizes))
	for _, n := range aliceSizes {
		aliceSum += n
		aliceBoxes[n] = struct{}{}
	}
	bobSum := 0
	for _, n := range bobSizes {
		bobSum += n
	}

	target := (aliceSum + bobSum) / 2

	for _, bobBox := range bobSizes {
		if _, ok := aliceBoxes[aliceSum + bobBox- target]; ok {
			return []int{aliceSum + bobBox - target, bobBox}
		}
	}
	panic("unreachable")
}