思路
此題,我們從貪心算法的角度進行思考。通過計算凈消耗,如果總的凈消耗小于0,說明無論如何都不能環路行駛一周。我們通過定義一個start起點,通過遍歷數組計算凈消耗,如果凈消耗小于0,重新置0,start更改為下一個坐標,然后重新計算。最后返回start
class Solution:def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:total=0for i in range(len(gas)):total+=gas[i]-cost[i]if total<0:return -1start=0sum=0for i in range(len(gas)):sum+=gas[i]-cost[i]if sum<0:sum=0start=i+1return start