力扣2187.完成旅途的最少时间

力扣2187.完成旅途的最少时间

朴素做法

  • 二分答案

cpp 复制代码
  class Solution {
      long long check(vector<int> time,long long k)
      {
          long long res=0;
          for(auto t:time)
              res += (long long)k/t;
          return res;
      }
  public:
      long long minimumTime(vector<int>& time, int totalTrips) {
          int n = time.size();
          sort(time.begin(),time.end());
          long long l=time[0]  - 1,r=(long long)totalTrips*time[0];
          while(l<r)
          {
              long long mid = l + r >> 1;
              if(check(time,mid) < (long long)totalTrips) l = mid + 1;
              else r = mid;
          }
          return l;
      }
  };

优化

  • 内联函数

  • 库函数min

cpp 复制代码
  class Solution {
  public:
      long long minimumTime(vector<int>& time, int totalTrips) {
          //内联函数 比外部函数快一倍
          auto check = [&](long long x) -> bool
          {
              long long res=0;
              for(int t : time)
              {
                  res += x/t;
                  if(res >= totalTrips) return true;
              }
              return false;
          };
          //求最小值
          int min_t = ranges::min(time);
          long long l=min_t,r=(long long)totalTrips*min_t;
          while(l<r)
          {
              long long mid = l + r >> 1;
              //说明当前mid时res >= total
              if(check(mid)) r = mid;
              else l = mid + 1;
          }
          return r;
      }
  };
相关推荐
lUie INGA1 小时前
在2023idea中如何创建SpringBoot
java·spring boot·后端
geBR OTTE2 小时前
SpringBoot中整合ONLYOFFICE在线编辑
java·spring boot·后端
Porunarufu2 小时前
博客系统UI自动化测试报告
java
Aurorar0rua3 小时前
CS50 x 2024 Notes C - 05
java·c语言·数据结构
Cosmoshhhyyy3 小时前
《Effective Java》解读第49条:检查参数的有效性
java·开发语言
布谷歌3 小时前
常见的OOM错误 ( OutOfMemoryError全类型详解)
java·开发语言
6Hzlia4 小时前
【Hot 100 刷题计划】 LeetCode 739. 每日温度 | C++ 逆序单调栈
c++·算法·leetcode
eLIN TECE4 小时前
springboot和springframework版本依赖关系
java·spring boot·后端
良木生香4 小时前
【C++初阶】:STL——String从入门到应用完全指南(1)
c语言·开发语言·数据结构·c++·算法