150強訪談簡單

加油站

“加油站”問題的詳細指南和 Python 實作。

問題陳述

簡單

一條環形路線上有n個加油站,第i個加油站的加油量為gas[i]。您有一輛油箱無限的汽車,從第 i 個車站到下一個 (i + 1) 個車站需要花費 cost[i] 的汽油。您在一個加油站帶著空油箱開始旅程。如果您可以順時針方向繞一圈,則返回起始加油站的索引,否則返回-1。如果存在解,則保證它是唯一的。

寫一個函數 canCompleteCircuit(gas: List[int], cost: List[int]) -> int

約束條件
  • n == len(gas) == len(cost)
  • 1 <= n <= 10^5
  • 0 <= gas[i], cost[i] <= 10^4

範例

Example 1
Input
gas = [1,2,3,4,5], cost = [3,4,5,1,2]
Output
3
Explanation

Start at station 3. tank = 4. Go to 4: cost 1, tank = 4-1+5 = 8. Go to 0: cost 2, tank = 8-2+1=7. Go to 1: cost 3, tank = 7-3+2=6. Go to 2: cost 4, tank = 6-4+3=5. Go to 3: cost 5, tank = 5-5=0. We reached back to station 3.

Example 2
Input
gas = [2,3,4], cost = [3,4,3]
Output
-1
Explanation

No station can complete the circuit.

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

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