其他分享
首页 > 其他分享> > 875. 爱吃香蕉的珂珂 (二分应用)

875. 爱吃香蕉的珂珂 (二分应用)

作者:互联网

 

labuladong 题解思路 难度中等

珂珂喜欢吃香蕉。这里有 n 堆香蕉,第 i 堆中有 piles[i] 根香蕉。警卫已经离开了,将在 h 小时后回来。

珂珂可以决定她吃香蕉的速度 k (单位:根/小时)。每个小时,她将会选择一堆香蕉,从中吃掉 k 根。如果这堆香蕉少于 k 根,她将吃掉这堆的所有香蕉,然后这一小时内不会再吃更多的香蕉。  

珂珂喜欢慢慢吃,但仍然想在警卫回来前吃掉所有的香蕉。

返回她可以在 h 小时内吃掉所有香蕉的最小速度 kk 为整数)。

 

示例 1:

输入:piles = [3,6,7,11], h = 8
输出:4

示例 2:

输入:piles = [30,11,23,4,20], h = 5
输出:30

示例 3:

输入:piles = [30,11,23,4,20], h = 6
输出:23

 

暴力超时 
class Solution {
public:
    int h_cnt_fun(int kk,vector<int>&piles) {
        int h_cnt = 0;
        for(auto pp :piles) {
            h_cnt+=(pp % kk == 0)?pp/kk:pp/kk+1;
        }
        return h_cnt;
    } 
    int minEatingSpeed(vector<int>& piles, int h) {
        sort(piles.begin(),piles.end());
        int n = piles.size();
        int res = piles.back();
        for (int kk = res;kk>=1;kk--) {
            int h_cnt = h_cnt_fun(kk,piles);
            if (h_cnt <=h) {
                res = min(res,kk);
            }
        }
        return res;
    }
};

 

 

 

class Solution {
public:
    long h_cnt_fun(int kk,vector<int>&piles) {
        long h_cnt = 0;
        for(auto pp :piles) {
            if (pp % kk == 0)  {
                h_cnt+= (pp / kk);
            } else {
                h_cnt += (pp / kk + 1);
            }
        }
        return h_cnt;
    } 
    int minEatingSpeed(vector<int>& piles, int h) {
        sort(piles.begin(),piles.end());
        int n = piles.size();
        int res = piles.back();
        int low = 1, high = res;
        while(low < high) {
            int mid = low + (high-low)/2;
            int h_cnt = h_cnt_fun(mid,piles);
            if (h_cnt<=h) {
                high = mid ;
                res = min(res,mid);
            } else {
                low = mid+1;
            }
        }
        return res;
    }
};

 

标签:二分,香蕉,cnt,piles,int,875,pp,kk
来源: https://www.cnblogs.com/zle1992/p/16590230.html