LeetCode 题解工作台
完成旅途的最少时间
给你一个数组 time ,其中 time[i] 表示第 i 辆公交车完成 一趟 旅途 所需要花费的时间。 每辆公交车可以 连续 完成多趟旅途,也就是说,一辆公交车当前旅途完成后,可以 立马开始 下一趟旅途。每辆公交车 独立 运行,也就是说可以同时有多辆公交车在运行且互不影响。 给你一个整数 tota…
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 二分·搜索·答案·空间
答案摘要
我们注意到,如果我们能在 时间内至少完成 趟旅途,那么在 $t' > t$ 时间内也能至少完成 趟旅途。因此我们可以使用二分查找的方法来找到最小的 。 我们定义二分查找的左边界 $l = 1$,右边界 $r = \min(time) \times \textit{totalTrips}$。每一次二分查找,我们计算中间值 $\textit{mid} = \frac{l + r}{2}$,然后计…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
给你一个数组 time ,其中 time[i] 表示第 i 辆公交车完成 一趟旅途 所需要花费的时间。
每辆公交车可以 连续 完成多趟旅途,也就是说,一辆公交车当前旅途完成后,可以 立马开始 下一趟旅途。每辆公交车 独立 运行,也就是说可以同时有多辆公交车在运行且互不影响。
给你一个整数 totalTrips ,表示所有公交车 总共 需要完成的旅途数目。请你返回完成 至少 totalTrips 趟旅途需要花费的 最少 时间。
示例 1:
输入:time = [1,2,3], totalTrips = 5 输出:3 解释: - 时刻 t = 1 ,每辆公交车完成的旅途数分别为 [1,0,0] 。 已完成的总旅途数为 1 + 0 + 0 = 1 。 - 时刻 t = 2 ,每辆公交车完成的旅途数分别为 [2,1,0] 。 已完成的总旅途数为 2 + 1 + 0 = 3 。 - 时刻 t = 3 ,每辆公交车完成的旅途数分别为 [3,1,1] 。 已完成的总旅途数为 3 + 1 + 1 = 5 。 所以总共完成至少 5 趟旅途的最少时间为 3 。
示例 2:
输入:time = [2], totalTrips = 1 输出:2 解释: 只有一辆公交车,它将在时刻 t = 2 完成第一趟旅途。 所以完成 1 趟旅途的最少时间为 2 。
提示:
1 <= time.length <= 1051 <= time[i], totalTrips <= 107
解题思路
方法一:二分查找
我们注意到,如果我们能在 时间内至少完成 趟旅途,那么在 时间内也能至少完成 趟旅途。因此我们可以使用二分查找的方法来找到最小的 。
我们定义二分查找的左边界 ,右边界 。每一次二分查找,我们计算中间值 ,然后计算在 时间内能完成的旅途数目。如果这个数目大于等于 ,那么我们将右边界缩小到 ,否则我们将左边界扩大到 。
最后返回左边界即可。
时间复杂度 ,其中 和 分别是数组 的长度和 ,而 是数组 中的最小值。空间复杂度 。
class Solution:
def minimumTime(self, time: List[int], totalTrips: int) -> int:
mx = min(time) * totalTrips
return bisect_left(
range(mx), totalTrips, key=lambda x: sum(x // v for v in time)
)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n * log(T)), where n is the number of buses and T is the maximum possible time derived from constraints. Space complexity is O(1) beyond the input array since no extra data structures are needed. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate quickly identifies binary search over the answer space as the key pattern.
- question_mark
The candidate demonstrates efficient computation of total trips for a given time.
- question_mark
The candidate correctly handles edge cases where buses have varying speeds or only one bus exists.
常见陷阱
外企场景- error
Attempting to simulate each trip sequentially, which exceeds time limits for large arrays.
- error
Miscalculating the number of trips by not using integer division.
- error
Setting incorrect binary search boundaries that skip the minimum time solution.
进阶变体
外企场景- arrow_right_alt
Find minimum time for buses with cooldown periods between trips.
- arrow_right_alt
Compute minimum time when buses have different start times.
- arrow_right_alt
Determine minimum time when only a subset of buses can be active at any moment.