入门力扣自学笔记280 C++ (题目编号:1123)(二分查找)(多看看)

2594. 修车的最少时间

题目:

给你一个整数数组 ranks ,表示一些机械工的 能力值 。ranksi 是第 i 位机械工的能力值。能力值为 r 的机械工可以在 r * n2 分钟内修好 n 辆车。

同时给你一个整数 cars ,表示总共需要修理的汽车数目。

请你返回修理所有汽车 最少 需要多少时间。

注意:所有机械工可以同时修理汽车。


示例 1:

输入:ranks = [4,2,3,1], cars = 10
输出:16
解释:
- 第一位机械工修 2 辆车,需要 4 * 2 * 2 = 16 分钟。
- 第二位机械工修 2 辆车,需要 2 * 2 * 2 = 8 分钟。
- 第三位机械工修 2 辆车,需要 3 * 2 * 2 = 12 分钟。
- 第四位机械工修 4 辆车,需要 1 * 4 * 4 = 16 分钟。
16 分钟是修理完所有车需要的最少时间。

示例 2:

输入:ranks = [5,1,8], cars = 6
输出:16
解释:
- 第一位机械工修 1 辆车,需要 5 * 1 * 1 = 5 分钟。
- 第二位机械工修 4 辆车,需要 1 * 4 * 4 = 16 分钟。
- 第三位机械工修 1 辆车,需要 8 * 1 * 1 = 8 分钟。
16 分钟时修理完所有车需要的最少时间。

提示:

  • 1 <= ranks.length <= 10^{5}
  • 1 <= ranks[i] <= 100
  • 1 <= cars <= 10^{6}

代码:

class Solution {
public:
    long long repairCars(vector& ranks, int cars) {
        long long upper_bound = (long long)ranks[0] * cars * cars, lower_bound = 0;
        return binary_search(0, upper_bound, cars, ranks);
    }

    bool pass(vector& ranks, int cars, long long& bound)
    {
        for(auto it = ranks.begin(); it != ranks.end(); it++)
        {
            int fixable = sqrt(bound / *it);
            cars -= fixable;
            if(cars <= 0)
                return true;
        }
        return false;
    }

    long long binary_search(long long begin, long long end, int cars, vector& ranks)
    {
        long long mid;
        while(begin < end)
        {
            mid = (begin + end) / 2;
            if(pass(ranks, cars, mid))
                end = mid;
            else
                begin = mid + 1;
        }
        if(begin == mid + 1)
            return begin;
        else
            return end;
    }
};

 

你可能感兴趣的:(力扣算法学习,leetcode,c++,算法)