https://leetcode.com/problems/gas-station/
这道题暴力的解释可以的 但是超时
def canCompleteCircuit(gas, cost):
length=len(gas)
for i in range(length):
sgas=0
scos=0
for j in range(length):
if i+j<length:
sgas=sgas+gas[i+j]
scos=scos+cost[i+j]
else:
sgas=sgas+gas[j-i-1]
scos=scos+cost[j-i-1]
if sgas<scos:
break
else:
if j==length-1:
return i
return -1
后来想不到别的算法 然而有个网友给了一些可以提高效率的方法
假设从A到P都能正常走 然而从A到P+1点发现走到半路没有油了
那么 下次走 直接从P+1点开始做起点
从A和P+1中间的任何一点都不能顺利走到P+1
原因在于 假设C点开始走 那么因为A能走到C 说明 A到C后邮箱里的油Lac是》=0
从A到P+1点油小于0 从C到P+1 邮箱里还少了从A到C的Lac的量的油 更不可能走到P+1点了
class Solution:
# @param {integer[]} gas
# @param {integer[]} cost
# @return {integer}
def canCompleteCircuit(self,gas, cost):
length=len(gas)
list=[]
for i in range(length):
list.append(gas[i]-cost[i])
start=0
while start<length:
sum=0
n=0
for j in range(length):
sum=sum+list[(start+j)%length]
n=n+1
if sum<0:
start=start+n
break
if j==length-1 and sum>=0:
return start
return -1