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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。