LeetCode:875 1011

LeetCode:875 1011_第1张图片

class Solution {
public:
    int minEatingSpeed(vector& piles, int H) {
        int sz = piles.size();
        if (H < sz)
            return -1;
        int maxNum = *max_element(piles.begin(), piles.end());
        if (H == sz)
            return maxNum;
        int lo = 1, hi = maxNum;
        int mid;
        while (lo < hi - 1) {
            mid = lo + (hi - lo) / 2;
            int time = helper(piles, mid);
            if (time > H) 
                lo = mid + 1;
            else
                hi = mid;
        }
        int time1 = helper(piles, lo);
        int time2 = helper(piles, hi);
        if (time1 > H)
            return hi;
        else if (time2 > H)
            return lo;
        else 
            return lo;
    }
private:
    int helper(vector& piles, int num) {
        int ret = 0;
        for (int pile : piles) {
            ret += (pile / num + (pile % num ? 1 : 0));
        }
        return ret;
    }
};

LeetCode:875 1011_第2张图片

class Solution {
public:
    int shipWithinDays(vector& weights, int D) {
        int sz = weights.size();
        int lo = 0, hi = 0;
        for (int weight : weights) {
            lo = max(lo, weight);
            hi += weight;
        }
        if (D >= sz)
            return lo;
        if (D == 1)
            return hi;
        int mid;
        while (lo < hi) {//这样写的话,最好最后lo和hi的都检查一下
            mid = lo + (hi - lo) / 2;
            int d = helper(weights, mid);
            if (d > D) 
                lo = mid + 1;
            else
                hi = mid;
        }
        /*int d = helper(weights, hi);
        if (d <= D)
            return hi;
        else
            return lo;*/
        return lo;
    }
private:
    int helper(vector& weights, int capacity) {//返回需要几天
        int ret = 1;
        int i = 0;
        int now = 0;
        while (i < weights.size()) {
            if (weights[i] + now <= capacity) 
                now += weights[i];
            else {
                ++ret;
                now = weights[i];
            }
            ++i;
        }
        return ret;
    }
};

这两题就是不要想复杂了的典范,直接二分法暴力搜索。
要说两题的共性,应该都是取值有明确的上下限,最终的结果是一个值,然后这个值的一边行,另一边不行,要我们求到这个值。应该可以想到是二分法。

类似一题:
https://blog.csdn.net/weixin_43462819/article/details/100693879

你可能感兴趣的:(Leetcode)