本文主要是介绍力扣2187.完成旅途的最少时间,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
力扣2187.完成旅途的最少时间
朴素做法
-
二分答案
-
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
-
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 >= totalif(check(mid)) r = mid;else l = mid + 1;}return r;}};
这篇关于力扣2187.完成旅途的最少时间的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!