New Year, everyone Happy New Year ~ ~ Because of the new year, so seldom do the problem recently, today finally have time to play code 134. Gas station.
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.
A simple question, just think of a strategy is good. (seemingly greedy?)
On the code, in fact, the main idea is to see the current petrol enough to use.
Public classSolution { Public intCancompletecircuit (int[] Gas,int[] cost) { intG=0; intC=0; intTg=0; intTc=0; intRet=0; BooleanFlag =false; for(inti=0;i<cost.length;i++) {g+=Gas[i]; C+=Cost[i]; TG+=Gas[i]; TC+=Cost[i]; if(Gas[i]>cost[i] &&!flag) {ret=i; Flag=true; } if(tg<TC) {TG=0; TC=0; Flag=false; } } if(c<=g)returnret; return-1; } Public Static voidMain (string[] args) {solution S=Newsolution (); int[] gas =New int[]{2}; int[] Cost =New int[]{2}; System.out.println (S.cancompletecircuit (gas)); }}
[Leetcode] Gas station