题目简介:
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.
提炼内容:
何为合法出发点:
1、该点p的pCost值小于pGas值
2、该点的后续节点q,若其qCost值大于qGas值,那么p中汽油剩余值(remainingGas = pGas - pCost) + qGas >= qCost
3、以此类推
算法思想:
1、找出所有的非法出发点
2、将非法出发点存入list unablePos 中
3、不在list中的出发点即为合法出发点
4、若出发点全在list中,则无合法出发点,程序返回-1
代码:
class Solution(object):
def canCompleteCircuit(self, gas, cost):
#分别表示剩余汽油和所需汽油
remainingGas , needGas, i = 0, 0, 0
#用于保存非法出发点
unablePos = []
size = len(gas)
#对每个出发点进行遍历并判断其是否合法
while i < size:
#遇到非法出发点
if gas[i] < cost[i]:
#保存非法出发点
unablePos.append(i)
#若下一个点是合法出发点,则从该出发点反序遍历
#即遇到了gas: 3 4 5 第三个出发点
# cos: 2 3 6
if gas[(i + 1) % size] >= cost[(i + 1) % size]:
#得到该节点需要的汽油量
needGas = cost[i] - gas[i]
index = i
#反序遍历直到前面的剩余汽油量达到需要汽油量值
while remainingGas < needGas:
if i == index + size:
return -1
index -= 1
#更新剩余汽油量值
remainingGas += gas[index] - cost[index]
#下一次检查前,将两个值归0
remainingGas = 0
needGas = 0
#保存非法出发点,区间(index, i]内的出发点都是非法的,
#因为这些节点都不没有足够的汽油可以使用
unablePos.extend([(x + size) % size for x in range(i,index,-1)])
i += 1
#寻找合理出发点
pos = [[x,0] for x in range(size)]
for i in unablePos:
pos[i][1] = 1
for i in pos:
if i[1] == 0:
return i[0]
return -1