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

    问题:

    Koko吃香蕉的速度为K,

    有一组香蕉盘piles,每个盘里装有不同数量的香蕉,

    每小时Koko可以选择一盘吃完。

    若这一盘<K,那么这一小时Koko只能吃到这一盘数量的香蕉。

    若这一盘>K,那么这一小时Koko吃了K个香蕉。下一小时,继续吃完这一盘。

    求在给定的H小时中,吃完所有香蕉,最小的食用速度K。

    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
    
    Constraints:
    1 <= piles.length <= 10^4
    piles.length <= H <= 10^9
    1 <= piles[i] <= 10^9
    

      

    解法:二分查找(Binary Search)

    根据题意,本问题的

    • 最小速度l:0
    • 最大速度r:盘中最大香蕉数。max(piles)

    寻找m使得,

    用m的速度,消耗完所有piles所用时间 h<=H

    要找从最小速度到最大速度中,第一个(最小速度)能够使得 h<=H 满足的m

    代码参考:

     1 class Solution {
     2 public:
     3     //all piles will be eaten up by the time <=H
     4     int minEatingSpeed(vector<int>& piles, int H) {
     5         int l = 1, r = INT_MIN;
     6         for(int pile: piles) r=max(r,pile)+1;
     7         while(l<r) {
     8             int m = l+(r-l)/2;
     9             int h  = 0;
    10             for(int pile:piles) {
    11                 if(pile <= m) h++;
    12                 else {
    13                     h+=(pile/m);
    14                     h+=(pile%m?1:0);
    15                 }
    16             }
    17             if(h<=H) {//find first K: h<=H
    18                 r = m;
    19             } else {
    20                 l = m+1;
    21             }
    22         }
    23         return l;
    24     }
    25 };
  • 相关阅读:
    安装MySQL5.7.19 网上的文章参考 并做了部分修改
    从hadoop一路配置到spark
    java面试问题收集(2)
    JAVA的 IO NIO AIO笔记
    Shiro
    Spring注解使用注意点
    oracle RAC
    spark随笔
    Storm知识点笔记
    真机调试手机程序,电脑插上手机数据线虚拟机中的系统就死掉
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/13495780.html
Copyright © 2011-2022 走看看