入门力扣自学笔记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;
    }
};
相关推荐
晨曦(zxr_0102)4 分钟前
CSP-X 2024 复赛编程题全解(B4104+B4105+B4106+B4107)
数据结构·c++·算法
ai安歌5 分钟前
【Rust编程:从新手到大师】 Rust 控制流深度详解
开发语言·算法·rust
Shinom1ya_7 分钟前
算法 day 36
算法
·白小白8 分钟前
力扣(LeetCode) ——15.三数之和(C++)
c++·算法·leetcode
海琴烟Sunshine10 分钟前
leetcode 268. 丢失的数字 python
python·算法·leetcode
CL.LIANG13 分钟前
视觉SLAM前置知识:相机模型
数码相机·算法
无限进步_29 分钟前
深入理解C语言scanf函数:从基础到高级用法完全指南
c语言·开发语言·c++·后端·算法·visual studio
Lei_33596738 分钟前
[算法]十大排序
数据结构·算法·排序算法
m0_748240251 小时前
C++仿Muduo库Server服务器模块实现 基于Reactor模式的高性
服务器·c++·php
大数据张老师1 小时前
数据结构——堆排序
数据结构·算法·排序算法