自己开发的博客网站,欢迎访问 www.weiboke.online
875. Koko Eating Bananas
Koko loves to eat bananas. There are N piles of bananas, the i-th pile has piles[i] bananas. The guards have gone and will come back in H hours.
Koko can decide her bananas-per-hour eating speed of K. Each hour, she chooses some pile of bananas, and eats K bananas from that pile. If the pile has less than K bananas, she eats all of them instead, and won’t eat any more bananas during this hour.
Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back.
Return the minimum integer K such that she can eat all the bananas within H hours.
Example 1:
Input: piles = [3,6,7,11], H = 8
Output: 4
Example 2:
Input: piles = [30,11,23,4,20], H = 5
Output: 30
Example 3:
Input: piles = [30,11,23,4,20], H = 6
Output: 23
Note:
1.1 <= piles.length <= 10^4
2. piles.length <= H <= 10^9
3.1 <= piles[i] <= 10^9
Approach
1.有一个KoKo喜欢吃banana,然后它准备偷香蕉吃,有一个工人守着n个香蕉点,KoKo趁工人离去的时间H想将所有香蕉吃完,问你每小时吃多少香蕉才可以,每次在一个香蕉点吃完全部才能走,但是吃完的那个小时不再进食。给的数据可以知道KoKo一定可以吃完所有香蕉,然后它最坏的速度为这香蕉点中的最大值,最好的速度为1,当工人离去的时间足够长。所以我们二分查找(1~piles_max),不断缩小范围,直至最佳的速度。
2.right=mid,而不是right=mid-1,是因为我们不知道mid是不是最佳的速度,我们只有不断缩小范围直至只有这个可能,才能确定是最佳的速度。
3.left=mid+1,是因为此时这个mid肯定不是最佳速度,因为它吃不完,所以速度肯定是要比mid大的。
Code
class Solution {
public:
bool isvalid(vector<int>& piles,int speed,int H) {
int time = 0;
for (int i = 0; i < piles.size(); i++) {
int c = piles[i] / speed;
int e = piles[i] % speed>0?1:0;
time += (c + e);
}
return time <= H;
}
int minEatingSpeed(vector<int>& piles, int H) {
int max_banans = *max_element(piles.begin(), piles.end());
if (H == piles.size())return max_banans;
int left = 1, right = max_banans;
while (left < right) {
int mid = left + (right - left) / 2;
if (isvalid(piles, mid, H)) {
right = mid;
}
else {
left = mid + 1;
}
}
return left;
}
};