Leetcode notes: Gas Station, leetcodegas
I. Description
There are N gas stations along a circular route, where the amount of gas at station I is gas [I].
You have a car with an unlimited gas tank and it costs cost [I] of gas to travel from station I to its next station (I + 1 ). you begin the journey with an 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 gas stations on the ring road, and each gas station has gasolinegas[i]
Gasoline consumption from each gas station to the next stopcost[i]
Ask the gas station from which you can return to the starting point. If none of them can be returned,-1 is returned. The solution mentioned in the last question is unique.
Ii. Question Analysis
The time complexity of the following solutions is:O(n)
, Each station can increase the amount of fuel and the amount of fuel consumed by each segment is stored ingas
Andcost
You can set two variables:sum
It is used to determine whether there is enough fuel to reach the next gas station. Ifsum<0
, You need to move the departure station forward to a station;remainingGas
It is used to record the amount of fuel after the entire process of driving. Final, judgmentremainingGas
If it is greater than zero, the subscript of the Initial Station is returned. If all stations cannot complete the whole process-1
.
Iii. Sample Code
# Include <vector> using namespace std; class Solution {public: int canCompleteCircuit (vector <int> & gas, vector <int> & cost) {int remainingGas = 0; int resultIndex = 0; int sum = 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; // The fuel consumption for all gas stations is less than the consumption else return resultIndex; // solution }};
Several processing results:
Iv. Summary
This is an interesting question. This method is only one of multiple methods.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.