leetcode875爱吃香蕉的珂珂 (构造0-1数组|二分查找)

题目:
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; 时会出错。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值