题目
https://leetcode.com/problems/gas-station/
题目太长了,还是直接贴链接吧~
题目很长,但是理解起来还是比较容易的:
在一条环形的路上有N个加油站,每个加油站里有gas[i]的汽油,从第i个加油站到第i+1个加油站需要花费cost[i]的汽油。假设汽车的油箱可以装无数的汽油,判断一辆没有油的汽车是否可以从其中的某一个加油站出发并行驶一圈后返回该加油站。如果可以的话,返回起始加油站的下标,否则返回-1。
实现代码
class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
if sum(gas) < sum(cost):
return -1
length = len(gas)
startIndex,diff = 0,0
for i in range(length):
if gas[i] + diff < cost[i]:
startIndex = i + 1
diff = 0
else:
diff += gas[i]- cost[i]
return startIndex