题目:
875. Koko Eating Bananas
Medium
7.6K
352
Companies
Koko loves to eat bananas. There are n piles of bananas, the ith 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 will not eat any more bananas during this hour.
Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
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
最大的k 11
最小的k 1
也就是找1-max中最小的速度k
也就是找第一个1
符合time<=h
也就是
123456
000111 找最小的1
构造了01数组,这题里找第一个1
思路:
一:先拿到最大和最小的速度
二: 然后把思路改成01问题思路
解题小技巧:
比如这堆6个,一次吃四个,那是要向上取整,画二个小时
注意数组越界问题:比如mid-1,那么mid就不能为0
所以考虑就取最小速度,k=1的情况;
/**
* @param {number[]} piles
* @param {number} h
* @return {number}
*/
var minEatingSpeed = function(piles, h) {
let max=0;
//先找数组里的最大值即为最大速度,1为最小速度
for(let i=0;i<piles.length;i++){
max= Math.max(max,piles[i]);
}
let left=1;
let right=max;
while(left<=right){
mid=Math.floor(left+(right-left)/2);
if (canEatAll(piles,mid,h)){ //判断这个速度能不能吃完
if(!canEatAll(piles,mid-1,h)){
return mid;
}
right=mid-1;
}
else{
left=mid+1;
}
}
return -1;
};
function canEatAll(piles,mid,h){
let time=0;
for(let i=0;i<piles.length;i++){
let t=Math.floor(piles[i]/mid); //不要忘记math.floor 除法中取下
if(piles[i]%mid!=0){ //如果余数不为0;
t+=1;
}
time+=t;
}
return time<=h;
}
注意!!
一:
在 canEatAll 函数中,p 是遍历 piles 数组时的索引,而不是数组元素本身。应该改成 piles[p] 表示访问当前索引 p 对应的元素。
function canEatAll(piles,mid,h){
let time=0;
for(let p in piles){
let t=Math.floor(piles[p]/mid);
if(piles[p]%mid!=0){
t+=1;
}
time+=t;
}
return time<=h;
}
二:
在 let max; 前面需要给 max 一个初始值,否则 Math.max 无法正确比较。此外,在 canEatAll 函数中,需要将 time 变量初始化为 0,否则在计算 time+=t; 时会出错。