【问题描述】
There are N gas stations along a circular route, where the amount of gas at station i is gas[i]
.
You have a car with an unlimited gas tank and it costs cost[i]
of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1.
Note:
- If there exists a solution, it is guaranteed to be unique.
- Both input arrays are non-empty and have the same length.
- Each element in the input arrays is a non-negative integer.
【解决思路】
这道题目有两个比较关键的量。
一个是总量total,从站点0一直累计到最后一个站点。
另一个是累积量cumulation,如果累积到某个站点时cumulation<0(油量耗尽),则从下一个站点开始累积(更新累积的起点start)。
如果到最后total>=0(总加油量不小于耗油量),则说明遍历成功,返回累积的起点(start);否则说明遍历失败,返回-1。
【代码实现】
class Solution:
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
num = len(gas)
start = 0
total = 0 # 总量(0~num)
cumulation = 0 # 累计量(start~num)
for i in range(0, num):
total = total + gas[i] - cost[i]
cumulation = cumulation + gas[i] - cost[i]
# 如果邮箱空了,从下一个站点重新开始累积
if cumulation < 0:
start = i + 1
cumulation = 0
return (start if total >= 0 else -1)
'''
sol = Solution()
gas = [1,2,3,4,5]
cost = [3,4,5,1,2]
print(sol.canCompleteCircuit(gas, cost))
gas = [2,3,4]
cost = [3,4,3]
print(sol.canCompleteCircuit(gas, cost))
'''