Original title address: https://oj.leetcode.com/problems/gas-station/
Test instructions
There was N gas stations along a circular route, where the amount of gas at Station I was gas[i]
.
You had a car with an unlimited gas tank and it costs of gas to travel from station cost[i]
I to its next station (i+ 1). You begin the journey with a 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.
Note:
The solution is guaranteed to be unique.
Problem-solving ideas: This problem is also very tricky, I think it is difficult to think out. If sum (gas) <sum, then there must be no solution. Saving is to walk the end of a station mailbox remaining oil, if added gas[i] also can't go to the next station, then continue to set the next station as the starting point, and then check, is not very clever?
Code: Time Complexity O (n), Space complexity O (1)
classSolution:#@param gas, a list of integers #@param cost, a list of integers #@return An integer defCancompletecircuit (self, gas, cost):ifSUM (GAS) < sum (cost):return-1StartIndex=0 Saving=0 forIinchRange (len):ifGas[i] + Saving <Cost[i]: StartIndex= i + 1Saving=0Else: Saving+ = Gas[i]-Cost[i]returnStartIndex
[Leetcode] Gas station @ Python