🚌 完成旅途的最少时间
📝 题目描述
给你一个数组time
,其中time[i]
表示第i
辆公交车完成一趟旅途所需要花费的时间。
每辆公交车可以连续完成多趟旅途,也就是说,一辆公交车当前旅途完成后,可以立马开始下一趟旅途。每辆公交车独立运行,也就是说可以同时有多辆公交车在运行且互不影响。
给你一个正整数totalTrips
,表示所有公交车总共需要完成的旅途数目。请你返回完成至少totalTrips
趟旅途需要花费的最少时间。
📋 代码模版
java
class Solution {
public long minimumTime(int[] time, int totalTrips) {
}
}
typescript
function minimumTime(time: number[], totalTrips: number): number {
}
💡 提示
🚀 示例
🖊️ 题解
设
根据上述单调性,我们可以使用二分查找算法,找出满足条件
二分查找的下限可以设置为
综上所述,在区间
为了进一步提高算法效率,我们还可以对
java
class Solution {
public long minimumTime(int[] time, int totalTrips) {
long minT = time[0];
for (int tm : time) {
minT = Math.min(tm, minT);
}
long low = minT, high = minT * totalTrips;
while (low <= high) {
long mid = low + ((high - low) >> 1);
if (check(time, totalTrips, mid)) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return low;
}
private boolean check(int[] time, int totalTrips, long t) {
int trips = 0;
for (int i = 0; i < time.length && trips < totalTrips; i++) {
trips += t / time[i];
}
return trips >= totalTrips;
}
}
typescript
function minimumTime(time: number[], totalTrips: number): number {
const check = (t: number): boolean => {
let trips = 0;
for (let i = 0; i < time.length && trips < totalTrips; i++) {
trips += Math.floor(t / time[i]);
}
return trips >= totalTrips;
}
const minT = Math.min(...time);
let low = minT, high = minT * totalTrips;
while (low <= high) {
const mid = low + Math.floor((high - low) / 2);
if (check(mid)) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return low;
}
💭 复杂度分析
基于二分查找
的解决方案的复杂度分析如下。
- 时间复杂度:
,其中 为二分查找的上下限之差, 为数组长度。 - 空间复杂度:
。