如果想在 V2EX 获得更好的推广效果,欢迎了解 PRO 会员机制:
https://www.v2ex.com/pro/about

如果你经常使用铜币置顶主题,持有 V2EX Solana Token 会在每日签到时获得额外铜币:
https://www.v2ex.com/solana
hakunamatata11
V2EX  ›  推广

[leetcode/lintcode 题解] Facebook 面试题:爱吃香蕉的珂珂

  •  
  •   hakunamatata11 · Jul 1, 2020 · 1129 views
    This topic created in 2191 days ago, the information mentioned may be changed or developed.

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

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

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

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

    • 1 <= piles.length <= 10^4
    • piles.length <= H <= 10^9
    • 1 <= piles[i] <= 10^9

    在线评测地址: https://www.lintcode.com/problem/koko-eating-bananas/?utm_source=sc-v2ex-fks

    样例 1:

    输入: piles = [3,6,7,11], H = 8
    输出: 4
    解释:6->4*2,7->4*2,11->4*3,3->4*1
    

    样例 2:

    输入: piles = [30,11,23,4,20], H = 5
    输出: 30
    解释:4->30*1,11->30*1,20->30*1,23->30*1,30->30*1
    

    [题解]

    采用二分的解法

    public class Solution {
        /**
         * @param piles: an array
         * @param H: an integer
         * @return: the minimum integer K
         */
        public int minEatingSpeed(int[] piles, int H) {
            // Write your code here
            int l = 1, r = 1000000000;
            while (l < r) {
                int m = (l + r) / 2, total = 0;
                for (int p : piles) 
                    total += (p + m - 1) / m;
                if (total > H) 
                    l = m + 1; 
                else 
                    r = m;
            }
            return l;
        }
    

    更多语言代码参见:https://www.jiuzhang.com/solution/koko-eating-bananas/?utm_source=sc-v2ex-fks

    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   946 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 20:26 · PVG 04:26 · LAX 13:26 · JFK 16:26
    ♥ Do have faith in what you're doing.