[leetcode]875. Koko Eating Bananas

162 篇文章 0 订阅
53 篇文章 0 订阅

[leetcode]875. Koko Eating Bananas


Analysis

直男真可怕—— [每天刷题并不难0.0]

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.
在这里插入图片描述

Explanation:

二分查找实现,查找区间是[1, max(piles)]

Implement

class Solution {
public:
    int minEatingSpeed(vector<int>& piles, int H) {
        sort(piles.begin(), piles.end());
        int l = 1, r = piles[piles.size()-1];
        int cnt;
        int k;
        while(l<r){
            k = l+(r-l)/2;
            cnt = 0;
            for(int p:piles)
                cnt += ceil((double)p/k);//这里一定要先用double转换一下类型
                //cnt += (p+k-1)/k;  这一行其实跟上一行是一样的意思,从讨论区一个大神那里看来的
            if(cnt > H)
                l = k+1;
            else
                r = k;
        }
        return l;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值