875. Koko Eating Bananas
https://leetcode.com/problems/koko-eating-bananas/
Input: piles = [3,6,7,11], h = 8
Output: 4Input: piles = [30,11,23,4,20], h = 5
Output: 30Input: piles = [30,11,23,4,20], h = 6
Output: 23Solution:
Last updated
https://leetcode.com/problems/koko-eating-bananas/
Input: piles = [3,6,7,11], h = 8
Output: 4Input: piles = [30,11,23,4,20], h = 5
Output: 30Input: piles = [30,11,23,4,20], h = 6
Output: 23Last updated
int minEatingSpeed(int[] piles, int H);// 定义:速度为 x 时,需要 f(x) 小时吃完所有香蕉// f(x) 随着 x 的增加单调递减int f(int[] piles, int x) { int hours = 0; for (int i = 0; i < piles.length; i++) { hours += piles[i] / x; if (piles[i] % x > 0) { hours++; } } return hours;}public int minEatingSpeed(int[] piles, int H) { int left = 1; // 注意,right 是开区间,所以再加一 int right = 1000000000 + 1; // ...}public int getFinishedHours(int[] piles, int speed)
{
int result = 0;
for(int count: piles)
{
result += count/speed;
if(count%speed > 0)
{
result++;
}
}
return result;
}class Solution {
public int minEatingSpeed(int[] piles, int h) {
int left = 1;
int right = 1000000000+1;
while(left + 1 < right)
{
int mid = left+(right-left)/2;
if(getFinishedHours(piles, mid) > h)
{
left = mid;
}
else
{
right = mid;
}
}
if(getFinishedHours(piles, left) <= h) return left;
if(getFinishedHours(piles, right) <= h) return right;
return -1;
}
public int getFinishedHours(int[] piles, int speed)
{
int result = 0;
for(int count: piles)
{
result += count/speed;
if(count%speed > 0)
{
result++;
}
}
return result;
}
}