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 cost[i] of the gas-to-travel from station 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.
First of all to determine the total oil enough consume, if the total oil is less than the total consumption that must be out of the way. Second, the process of whether the remaining oil will be less than 0, if less than 0 that can only start from the next station. Walk through it to get an answer.
1. Compare total gas and total cost, if total gas<total cost
Return-1
2. Iterate the whole station, Rest+=gas[i]-cost[i] If rest<0, search start from the next I
Return station
Class solution: # @param gas, a list of integers # @param cost, a list of integers # @return an integer de F Cancompletecircuit (self, gas, cost): if sum (gas) <sum (cost): return-1 Else: pre=0 rest=0 station=0 for index in range (len): Rest+=gas[index]-cost[index] if rest<0: pre+= Rest rest=0 station=index+1 return station
Gas station Leetcode Python