Using Binary Search Template:

class Solution {
    public int minEatingSpeed(int[] piles, int h) {
        int l=1, r=0;
        for(int i=0;i<piles.length;i++){
            r = Math.max(r, piles[i]);
        }
    
        while(l+1<r){
            int mid = (l+r)/2;
            int res = eat(piles, mid);
            if(res<=h){
                r=mid;
            }else{
                l=mid;
            }
        }
        if(eat(piles, l)<h)
            return l;
        else
            return r;
    }
    
    private int eat(int[] piles, int k){
        int res = 0;
        for(int i=0;i<piles.length;i++){
            if(piles[i]%k==0){
                res+=piles[i]/k;
            }else
                res+=piles[i]/k+1;
        }
        return res;
    }
}

 

posted on 2022-03-24 05:47  阳光明媚的菲越  阅读(17)  评论(0编辑  收藏  举报