Problem:
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.
Hide TagsGreedyTest instructions: The car from a gas station, refueling, consumption, find the only one can return to the original point of the gas station
Thinking:
(1) The algorithm is relatively simple, gasoline allowance is negative when not feasible, greedy strategy
(2) I have just started to adopt the dfs+ scissor branching way, the submission timed out, but this idea applies more broadly
(3) The use of array processing to avoid the cost of recursive function calls
Code
dfs+ Shear Branch: Timeout
Class Solution {Public:int cancompletecircuit (vector<int>& gas, vector<int>& cost) {int de P=0; int Maxdep=gas.size ()-1; if (maxdep<0) return 0; int fuel=0; BOOL Flag=true; for (int index=0;index<gas.size (); index++) {DFS (dep,maxdep,index,fuel,gas,cost,flag); if (flag) return index; Flag=true; } return-1; }protected:void dfs (int dep,int maxdep,int index,int fuel, vector<int> &gas, vector<int> &cost, bo Ol &flag) {if (!flag) return; Fuel+=gas[index]; Fuel-=cost[index]; if (fuel<0) {flag=false; Return } if (DEP==MAXDEP) {if (fuel<0) Flag=false; else flag=true; Return } dfs (DEP+1,MAXDEP, (index+1)%gas.size (), Fuel,gas,cost,flag); } };
Greedy strategy: AC
Time complexity O (n)
Class Solution {public: int cancompletecircuit (vector<int> &gas, vector<int> &cost) { int Total = 0; Int j =-1; for (int i = 0, sum = 0; i < gas.size (); ++i) { sum + = gas[i]-cost[i]; Total + = Gas[i]-cost[i]; if (Sum < 0) { j = i; sum = 0; } } Return Total >= 0? J + 1:-1;
Leetcode | | 134, gas station