There areNGas stations along a circular route, where the amount of gas at StationIIsGas [I]
.
You have a car with an unlimited gas tank and it costsCost [I]
Of gas to travel from StationITo 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.
Using Gas-cost to construct an array left, left [I] represents the amount of gas remaining after the I Station reaches the next stop;
Note: 1. remember to take the POs modulo and pull it back from beyond the position; 2. according to the aggregation analysis, the time complexity is O (n), because after a scan, you can determine the start position, and then append another N scans, so it is mostly 2n time. The Code is as follows:
Class solution {public: int cancompletecircuit (vector <int> & gas, vector <int> & cost) {int M = gas. size (); int COUNT = 0, sum = 0, Pos = 0, start = 0; vector <int> left; For (INT I = 0; I <m; I ++) left. push_back (gas [I]-cost [I]); For (INT I = 0; I <m; I ++) sum + = left [I]; if (sum <0) Return-1; sum = 0; while (count <m) {// use count to record the number of traveled sites sum + = left [POS]; pos = ++ POS % m; // modulo the POs value out of the range to 0, M % m = 0 both m + 1 POs and 0 if (sum <0) {sum = 0; Count = 0; Start = Pos ;} else {count ++ ;}} return start ;}};
Leetcode: Gas Station