[leetcode]875. Koko Eating Bananas

[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;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/85159010