LeetCode 之 875

Koko loves to eat bananas.  There are N piles of bananas, the i-th 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 won't eat any more bananas during this hour.

Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back.

Return the minimum integer K such that she can eat all the bananas within H hours.

 

- H时间

- 一次只能吃一把

- K K*H 吃的最大数量

- min K 求出最小的 K

1 -> N(尝试) 20(MAX)

 

1. 把香蕉表达一下 数据结构

处理的数据 .length H

[3, 6, 7, 11] H = 8

K = 4

[30, 11, 23, 4, 20] H = 5

K = 30

[30, 11, 23, 4, 20] H = 6

K = 23

 

2. Max 规则 Max(arr)

3. Max-- 正好在 H 小时内吃完

4. 怎么可以高效 二分查找

 

- koko

1. while(1 -> Math.max(...piles)) 每把香蕉花的小时数加起来 piles => pile => Math.ceil(pile/low)

- 减少写尝试

1. -> max 二分查询

2. 寻找到不能吃完的K值,将K值作为最小值继续寻找。

3. 寻找到能吃完的K值,也将其认为是非最小值。

4. 以防最小值是HI - 1 的情况 且 LO-1不能吃完将循环条件设置为 LO<=HI-1

5. 防止HI就是最小值的情况,将有一个判断防止重复的取中间的步骤

 

 

var minEatingSpeed = function (piles, H = 8) {
    let lo = 1, //min
        hi = Math.max(...piles),
        temp; //max

    while (lo <= hi - 1) {

        
        if (canEatAllBananas(piles, H, lo)) {
            console.log(`可以被吃完   hi:${hi} + lo:${lo}`);
            hi = lo;
            lo = temp;

        } else {
            console.log(`不可以被吃完   hi:${hi} + lo:${lo}`);
            temp = lo + 1;
            // 提前退出,防止产生无限循环的情况 例如 实例一 minEatingSpeed([3,6,7,11],8)
            if(lo == Math.floor((hi + lo) / 2)){
                return hi;
            }
            // 模拟C语言情况下的整数的四舍五入
            lo = Math.floor((hi + lo) / 2);
        }
    }

    return Math.floor(hi);

}

// 查找是否能吃完
function canEatAllBananas(piles, H, lo) {
    let h = 0;
    for (let pile of piles) {
        h += Math.ceil(pile / lo);
    }
    return h <= H;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值