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.
这道题最容易想到的方法就是从一个点出发,看看能不能走回到起点,如果可以返回起点的index, 不行的话再试下一个点。但是超时。
这个超时算法中有两点值得注意。
a) L13. 对于 int a 怎么计算 a 在 循环群[0,1,2,n-1]上的index?
b) L21-L22,可以使用一个变量记录是哪一步跳出的。然后判断是不是最后一步跳出的。
class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
n = len(gas)
for i in range(n):
fule = 0
step = 0
for j in range(n):
index = (i+j +1)%n -1
fule += gas[index]
step = j
if fule < cost[index]:
break
else:
fule -= cost[index] if step == n-1:
return i
return -1
一下三条原则摘自: http://bangbingsyb.blogspot.com/2014/11/leetcode-gas-station.html
性质1. 对于任意一个加油站i,假如从i出发可以环绕一圈,则i一定可以到达任何一个加油站。显而易见。
class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
n = len(gas)
start = 0
netGasSum = 0
curGasSum = 0 for i in range(n):
netGasSum += gas[i] - cost[i]
curGasSum += gas[i] - cost[i]
if curGasSum < 0:
start = i+1
curGasSum = 0; if netGasSum < 0:
return -1
return start