class Solution {
public int minEatingSpeed(int[] piles, int h) {
// 套用二分查找左侧边界模板
int left = 1, right = getMaxPile(piles);
while (left <= right) {
int mid = left + (right - left) / 2;
if (canFinishAll(piles, mid, h)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
// 辅助函数,能否吃完香蕉
boolean canFinishAll(int[] piles, int speed, int h) {
// 吃完香蕉的总时间
int time = 0;
for (int pile : piles) {
time += pile / speed;
if (pile % speed != 0)
time++;
}
return time <= h;
}
// 求数组中最大值
int getMaxPile(int[] piles) {
int max = 0;
for (int n : piles)
max = Math.max(n, max);
return max;
}
}
leetcode-875-爱吃香蕉的珂珂
最新推荐文章于 2021-11-28 11:56:15 发布