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;
        }
    }
    
     
  • 相关阅读:
    将aspx页面编译成dll
    Jquery 验证数字
    c#反编译生成DLL过程
    c#进制转换
    Spring Mvc 实例
    wamp phpMyAdmin error #1045
    Tomcat相关知识点总结(jsp)
    Java ---学习笔记(泛型)
    Java IO ---学习笔记(文件操作与随机访问文件)
    Java IO ---学习笔记(字符流)
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12066571.html
Copyright © 2011-2022 走看看