二分法

1011. 在 D 天内送达包裹的能力

思路:二分法

class Solution {
public:
    int shipWithinDays(vector<int>& weights, int D) {
        int high = 500*50000+1;
        int low = 0;
        int mid;

        while(low < high){
            mid = (low + high) / 2;
            if(canHold(weights, D, mid)){
                // 能承载
                high = mid;
            }else{
                // 不能承载
                low = mid + 1;
            }
        }
        return low;
    }

    bool canHold(vector<int>& weights, int D, int K){
        int cur = K; // cur表示目前可以承载的重量
        for(int i = 0; i < weights.size(); i++){
            if(weights[i] > K){
                return false;
            }
            if(weights[i] > cur){
                // 不能放下了
                D--;
                cur = K;
            }
            cur -= weights[i];
        }
        return D > 0;
    }
};

875. 爱吃香蕉的珂珂

class Solution {
public:
    int minEatingSpeed(vector<int>& piles, int H) {
        // H 小时
        int low = 1;
        auto highpos = max_element(piles.begin(), piles.end()); // 找最大值
        int high = *highpos;
        int mid;

        while(low < high){
            mid = (low + high) / 2;
            if(canEat(piles, H, mid)){
                // 能吃
                high = mid;
            }else{
                // 不能吃
                low = mid+1;
            }
        }
        return low;
    }

    bool canEat(vector<int>& piles, int H, int K){
        // H 小时
        // 速度 K
        int sum = 0;
        for(int i = 0; i < piles.size(); i++){
            sum += ceil(piles[i] * 1.0 / K); // 向上取整
        }
        return sum <= H;
    }
};

你可能感兴趣的:(C++,刷题)