zoukankan      html  css  js  c++  java
  • 875. Koko Eating Bananas

    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.

    Example 1:

    Input: piles = [3,6,7,11], H = 8
    Output: 4
    

    Example 2:

    Input: piles = [30,11,23,4,20], H = 5
    Output: 30
    

    Example 3:

    Input: piles = [30,11,23,4,20], H = 6
    Output: 23
    

    Note:

    • 1 <= piles.length <= 10^4
    • piles.length <= H <= 10^9
    • 1 <= piles[i] <= 10^9
    class Solution {
        public int minEatingSpeed(int[] piles, int H) {
            int left = 1, right = (int)1e9;
            while(left < right){
                int mid = left + (right - left) / 2, hour = 0;
                for(int p : piles){
                    hour += Math.ceil(p / mid);
                }
                if(hour < H) right = mid;
                else left = mid + 1;
            }
            return left;
        }
    }

    虽然不是同一时间,但是是同一个类型,干就完事了兄弟们,奥里给

    和上面两道一样。

    Math.ceil()是进一法取整。但是这道题不能直接用是int的话会有精度损失而且慢,而是用

    (p + mid - 1) / mid
    -1是防止p==mid的现象
    class Solution {
        public int minEatingSpeed(int[] piles, int H) {
            int left = 1, right = (int)1e9;
            while(left < right){
                int mid = left + (right - left) / 2, hour = 0;
                for(int p : piles){
                    hour += (p + mid - 1) / mid;
                }
                if(hour > H) left = mid + 1;
                else right = mid;
            }
            return left;
        }
    }
    
     

     如果一定要用的话要

    class Solution {
        public int minEatingSpeed(int[] piles, int H) {
            int left = 1, right = (int)1e9;
            while(left < right){
                int mid = left + (right - left) / 2, hour = 0;
                for(float p : piles){
                    hour += Math.ceil(p / mid);
                }
                if(hour > H) left = mid + 1;
                else right = mid;
            }
            return left;
        }
    }
    
     
  • 相关阅读:
    音视频之PCM转WAV(八)
    音视频之播放YUV数据(十二)
    音视频之视频录制(十)
    报错error: missing D__STDC_CONSTANT_MACROS / #define __STDC_CONSTANT_MACROS
    Vue组件广告滚动
    配置Vue中@符,出现路径提示
    iOS WKWebView后台崩溃问题排查
    vue element 静态分页
    vue Vue __ob__: Observer 取值
    csdn 复制代码
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12066571.html
Copyright © 2011-2022 走看看