I. Title Description
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.
There are n petrol stations on the ring route, petrol at each petrol station, petrol gas[i]
from each petrol station to the next station, and a cost[i]
gas station where you can go back to the starting point, and if not, return-1, and the last topic mentions that the solution is unique.
Two. Topic analysis
The time complexity of the following solution is: O(n)
, each station can be the amount of fuel and the fuel consumption of each distance is stored in gas
and cost
, you can set two variables: sum
to determine whether there is currently enough fuel to go to the next gas station, if sum<0
you need to move the departure station forward a station remainingGas
used to record the amount of oil after the vehicle has been opened for the entire process. Finally, if the judgment is remainingGas
greater than 0, the index is returned to the initial station, and if all stations are unable to complete the journey, they will return -1
.
Three. Sample code
#include <vector>using namespace STD;classSolution { Public:intCancompletecircuit ( vector<int>&gas, vector<int>&cost) {intRemaininggas =0;intResultindex =0;intsum =0; for(size_t i =0; I < gas.size (); ++i)//traverse the situation of each station{Remaininggas + = Gas[i]-cost[i]; Sum + = Gas[i]-cost[i];if(Sum <0) {sum =0; Resultindex = i +1; } }if(Remaininggas <0)return-1;//petrol filling at all stations is less than consumption Else returnResultindex;//Have solutions}};
Several processing results:
Four. Summary
The problem is a more interesting one, the method is only one of many methods.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode Notes: Gas station