🍌 爱吃香蕉的珂珂
📝 题目描述
珂珂喜欢吃香蕉。这里有n
堆香蕉,第i
堆中有piles[i]
根香蕉。警卫已经离开了,将在h
小时后回来。
珂珂可以决定她吃香蕉的速度k
(单位:根/小时)。每个小时,她将会选择一堆香蕉,从中吃掉k
根。如果这堆香蕉少于k
根,她将吃掉这堆的所有香蕉,然后在这一小时内不会再吃更多的香蕉。
珂珂喜欢慢慢吃,但仍然想在警卫回来前吃掉所有的香蕉。
返回她可以在h
小时内吃掉所有香蕉的最小速度k
(k
为正整数)。
📋 代码模版
java
class Solution {
public int minEatingSpeed(int[] piles, int h) {
}
}
typescript
function minEatingSpeed(piles: number[], h: number): number {
}
💡 提示
🚀 示例
🖊️ 题解
设
根据上述单调性,我们可以使用二分查找算法,找出满足条件
二分查找的下限可以设置为
综上所述,在区间
为了进一步提高算法效率,我们还可以对
java
class Solution {
public int minEatingSpeed(int[] piles, int h) {
int low = 1, high = piles[0];
for (int pile : piles) {
high = Math.max(high, pile);
}
while (low <= high) {
int mid = low + ((high - low) >> 1);
if (check(piles, h, mid)) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return low;
}
private boolean check(int[] piles, int h, int k) {
int totalH = 0;
for (int i = 0; i < piles.length && totalH <= h; i++) {
totalH += (piles[i] + k - 1) / k;
}
return totalH <= h;
}
}
typescript
function minEatingSpeed(piles: number[], h: number): number {
const check = (k: number): boolean => {
let totalH = 0;
for (let i = 0; i < piles.length && totalH <= h; i++) {
totalH += Math.ceil(piles[i] / k);
}
return totalH <= h;
}
let low = 1, high = Math.max(...piles);
while (low <= high) {
const mid = low + Math.floor((high - low) / 2);
if (check(mid)) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return low;
}
💭 复杂度分析
基于二分查找
的解决方案的复杂度分析如下。
- 时间复杂度:
。其中 为数组中的最大值, 为数组长度。 - 空间复杂度:
。