入门力扣自学笔记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 <=
  • 1 <= ranks[i] <= 100
  • 1 <= cars <=

代码:

cpp 复制代码
class Solution {
public:
    long long repairCars(vector<int>& 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<int>& 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<int>& 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;
    }
};
相关推荐
OrangeJiuce38 分钟前
【QT中的一些高级数据结构,持续更新中...】
数据结构·c++·qt
程序员-King.3 小时前
【接口封装】——13、登录窗口的标题栏内容设置
c++·qt
学编程的小程4 小时前
LeetCode216
算法·深度优先
leeyayai_xixihah4 小时前
2.21力扣-回溯组合
算法·leetcode·职场和发展
01_4 小时前
力扣hot100——相交,回文链表
算法·leetcode·链表·双指针
萌の鱼4 小时前
leetcode 2826. 将三个组排序
数据结构·c++·算法·leetcode
Buling_04 小时前
算法-哈希表篇08-四数之和
数据结构·算法·散列表
AllowM4 小时前
【LeetCode Hot100】除自身以外数组的乘积|左右乘积列表,Java实现!图解+代码,小白也能秒懂!
java·算法·leetcode
RAN_PAND4 小时前
STL介绍1:vector、pair、string、queue、map
开发语言·c++·算法