题目链接:https://leetcode-cn.com/problems/koko-eating-bananas/
难度:中等
思路:二分搜索最小边界问题
代码:
class Solution {
public:
//若吃香蕉的速度是 x 根每小时,则需要 f(x) 小时吃完。
int f(const vector<int>& piles, const int x)
{
int hours = 0;
for (const auto& i: piles)
{
hours += i / x; //每堆吃完需要多少个小时
if ((i % x) > 0) //若这堆没吃完,则留到下一个小时再吃
hours++;
}
return hours;
}
int minEatingSpeed(const vector<int>& piles, const int h) {
int left = 1; //最小速度
int right = 1000000000 + 1; //最大速度,每小时最多吃一堆
while (left < right)
{
int mid = left + (right - left) / 2;
if (f(piles, mid) <= h)
right = mid; //缩小区间
else
left = mid + 1;
}
return left;
}
};
难点:
- 重点在于如何理解题目。因为是返回
最小速度
,因此确定是搜索左侧边界。 - 如何构建吃香蕉的速度 x 和时间的关系 f(x) 是难点。