leetcode 加油站——一次遍历

发布时间 2023-09-17 15:52:52作者: Aneverforget

 

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