Leetcode 875 KoKo Eats banana

时间:2024-10-27 18:49:10

题意: 有个哥们吃香蕉,array为吃的大小,想在h时间吃完,但是又想用最少的时间吃完
https://leetcode.com/problems/koko-eating-bananas/

答案:二分答案,形如xxxooo,我要找到第一个o,但是由于我l+1了,所以r-l不加一

class Solution {
public:
    int minEatingSpeed(vector<int>& piles, int h) {
        int l = 1;
        int r = *max_element(piles.begin(), piles.end());
        while(l < r) {
            int mid = l + (r - l) / 2;
            if(eat(piles, mid) <= h) {
                r = mid;
            } else {
                l = mid + 1;
            }
        }
        return l;
    }
    
    int eat(vector<int>& piles, int s) {
        int ret = 0;
        for(int i = 0; i < piles.size(); i++) {
            ret += ceil((double)piles[i]/s);
        }
        
        return ret;
    }
};