funcminEatingSpeed(piles []int, h int)int { // 起点:一次只吃一根香蕉 终点:一次最多吃掉最大那一堆香蕉 left, right := 1, max(piles...)
for left <= right { mid := left + (right - left) / 2 midValue := f(mid, piles) if midValue < h { right = mid - 1 } elseif midValue > h { left = mid + 1 } else { right = mid - 1 } }
// 由于不是搜索数组所以不会越界,只要搜索区间合理,一定能找出结果 return left }
funcf(x int, piles []int)int { hours := 0 for i := 0; i < len(piles); i++ { hours += piles[i] / x if piles[i] % x > 0 { hours += 1 } } return hours }
funcmax(values ...int)int { res := values[0] for _, v := range values { if v > res { res = v } } return res }
funcshipWithinDays(weights []int, days int)int { left, right := max(weights...), sum(weights...)
for left <= right { mid := left + (right - left) / 2 midValue := f(mid, weights) if midValue < days { right = mid - 1 } elseif midValue > days { left = mid + 1 } else { right = mid - 1 } }
return left }
funcf(x int, weights []int)int { days := 0 remains := 0 for i := 0; i < len(weights); i++ { if remains - weights[i] < 0 { remains = x days++ } remains -= weights[i] } return days }
funcmax(values ...int)int { res := values[0] for _, v := range values { if v > res { res = v } } return res }
funcsum(values ...int)int { res := 0 for _, v := range values { res += v } return res }