[leetcode] 875. 爱吃香蕉的珂珂(周赛)

875. 爱吃香蕉的珂珂

这题时间要求比较严格。。。

首先,将piles排序,然后二分查找。

总之,答案K肯定位于piles[?]piles[?+1]或者1piles[0]之间

所以我们先二分把?找到,然后再二分找到K即可

class Solution {
    public int minEatingSpeed(int[] piles, int H) {
        Arrays.sort(piles);
        if (H == piles.length) {
            return piles[piles.length - 1];
        }
        int left = 0;
        int right = piles.length - 1;
        int mid = (left + right) / 2;
        int midK = fun(piles, piles[mid]);
        while (right - left > 1) {
            if (midK < H) {
                right = mid;
            } else {
                left = mid;
            }
            mid = (left + right) / 2;
            midK = fun(piles, piles[mid]);
        }
        int ans = piles[left];
        if (left == 0) {
            ans = 1;
        }

        int ansLeft = ans;
        int ansRight = piles[right];
        int ansMid = (ansLeft + ansRight) / 2;
        while (ansLeft < ansRight) {
            if (!ok(piles, ansMid, H)) {
                ansLeft = ansMid + 1;
            } else {
                ansRight = ansMid;
            }
            ansMid = (ansLeft + ansRight) / 2;
        }
        return ansLeft;
    }

    int fun(int[] piles, int k) {
        int ans = 0;
        for (int pile : piles) {
            ans += pile / k;
            if (pile % k > 0) {
                ans++;
            }
        }
        return ans;
    }

    boolean ok(int[] piles, int k, int H) {
        long ans = 0;
        for (int pile : piles) {
            ans += pile / k;
            if (pile % k > 0) {
                ans++;
            }
            if (ans > H) {
                return false;
            }
            if (ans < 0) {
                return false;
            }
        }
        return true;
    }
}
posted @ 2018-07-22 11:41  ACBingo  阅读(1505)  评论(0编辑  收藏  举报