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

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