leetcode 加油站——一次遍历

class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
n=len(gas)
max_gas=0
rest=0
records=[]
start=0
for i in range(n):
tmp=gas[i]-cost[i]
records.append(tmp)
if sum(records)<0:
return -1
for i in range(n):
if rest>=0:
rest=rest+records[i]
#1、从非负处,才能开始出发。
#2、若从x到y,不能到达,则从x,到y,中间出发也不能达到y。
#当总gas>总cost,一次遍历可找出出发点。
if rest<0:
start=i+1
rest=0
if rest>=0:
return start
return -1

浙公网安备 33010602011771号