150强访谈简单

车队

“车队”问题的详细指南和 Python 实现。

问题陈述

简单

n 辆汽车沿着单车道前往同一目的地。目的地距离 target 英里。

给定两个整数数组 positionspeed,长度均为 n,其中 position[i] 是第 i 辆汽车的位置,speed[i] 是第 i 辆汽车的速度(以英里每小时为单位)。

一辆车永远无法超过它前面的另一辆车,但它可以追上它并以相同的速度并排行驶。较快的汽车将减速以匹配较慢的汽车的速度。忽略这两辆车之间的距离(假设它们位于同一位置)。

车队是一些以相同位置和相同速度行驶的非空汽车集合。一辆汽车也是一个车队。

返回将到达目的地的车队数量。

编写一个函数 carFleet(target: int, position: List[int], speed: List[int]) -> int

约束条件
  • n == len(position) == len(speed)
  • 1 <= n <= 10^5
  • 0 < target <= 10^6
  • 0 <= position[i] < target
  • 0 < speed[i] <= 10^6
  • All positions are unique

示例

Example 1
Input
target = 12, position = [10, 8, 0, 5, 3], speed = [2, 4, 1, 1, 3]
Output
3
Explanation

Cars at positions 10 and 8: car at 8 catches car at 10 (both arrive at time 1), forming 1 fleet. Car at 0: arrives at time 12. Car at 5: arrives at time 7. Car at 3: arrives at time 3, catches car at 5 at time 7, but car at 5 arrives at 7 too. Cars at 3 and 5 form a fleet. Total: 3 fleets.

Example 2
Input
target = 10, position = [3], speed = [3]
Output
1
Explanation

Only one car, so one fleet.

Example 3
Input
target = 100, position = [0, 2, 4], speed = [4, 2, 1]
Output
1
Explanation

All cars eventually form a single fleet.

Need a Hint?
考虑使用特定于堆栈的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。