funcmissingRolls(rolls []int, mean int, n int) []int { m := len(rolls) s := mean * (m + n) for _, roll := range rolls { s -= roll } if s < n || s > n*6 { returnnil } avg := s / n poor := s % n ans := make([]int, n) for i := 0; i < n; i++ { ans[i] = avg if i < poor { ans[i] += 1 } } return ans }
funcfindPeaks(mountain []int) []int { ans := []int{} for i := 1; i < len(mountain)-1; i++ { if mountain[i] > mountain[i-1] && mountain[i] > mountain[i+1] { ans = append(ans, i) } } return ans }
funcfindMissingAndRepeatedValues(grid [][]int) []int { n := len(grid) cnt := make([]int, n*n+1) for _, g := range grid { for _, x := range g { cnt[x]++ } } ans := make([]int, 2) for i := 1; i <= n*n; i++ { if cnt[i] == 0 { ans[1] = i } elseif cnt[i] == 2 { ans[0] = i } } return ans }
假设给第一个小朋友分了 x 个糖果,第二个小朋友分了 y 个糖果,那么第三个小朋友将分到 n−x−y 个糖果,只要他们分到的糖果小于 limit 即为一个合法的方案。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
funcdistributeCandies(n int, limit int)int { ans := 0 for x := 0; x <= limit; x++ { for y := 0; y <= limit; y++ { if x+y > n { break } if n-x-y <= limit { ans++ } } } return ans }