Leetcode 875. 爱吃香蕉的珂珂
1. 问题描述
思路
二分查找
代码
func minEatingSpeed(piles []int, h int) int {
sum := 0
for i := 0; i < len(piles); i++ {
sum += piles[i]
}
left, right := 1, sum
for left <= right {
mid := left + (right - left) / 2
hour := countHours(piles, mid)
if hour == h {
right = mid - 1
} else if hour < h {
right = mid - 1
} else {
left = mid + 1
}
}
return left
}
func countHours(piles []int, k int) int {
res := 0
for i := 0; i < len(piles); i++ {
var h int
if piles[i] % k == 0 {
h = piles[i] / k
} else {
h = piles[i] / k + 1
}
res += h
}
return res
}
|