Problem:
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, otherwise return -1.
Note:
The solution is guaranteed to be unique.
Solution:
class Solution:
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
no_stations = len(gas)
gas_left = sum(gas)- sum(cost) # 如果gas总数大于cost,则一定有解
if gas_left >= 0: # there is a solution
start = 0
gas_hold = 0
while start < no_stations:
for route in range(no_stations):
gas_hold = gas_hold + gas[(start+route)%no_stations]
gas_cost = cost[(start+route)%no_stations]
gas_hold = gas_hold - gas_cost
if gas_hold < 0:
gas_hold = 0
start = start + route
break
if route == no_stations-1 and gas_hold >= 0:
return start
start = start + 1
return -1
第一次采用笨拙的全部遍历方法,超时。
该算法注意两个地方:
1. 如果从A不能到达B,则中间的任意一个点均不能到达B。(B为从A出发不能到达的第一个点),所以在搜索A-B不成功,下一次迭代搜索起点可以直接设置为B点。
2.总gas小于总cost时无解。