[Leedcode 134] Gas station

Source: Internet
Author: User

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.

 Public classSolution {/*we start from 0 to its starting point experiment, add Restgas + = Gas[i]-cost[i], once I encounter restgas<0, then the current selection of the starting point beg No, need to re-select, at this time we should not go back to use beg+1 as a new Point, because in the beg place, must have gas>=cost, explain beg+1 to I where the total gas must be less than the total cost, choose any one of them as a starting point or not, so should skip these points, to i+1 as a new starting point, traverse to size-1 can end , if we find a possible starting point, we have to verify, go through (total), if there is no problem then the explanation can be. *//*in fact, the essence is: the beginning of the path is divided into two paragraphs, the total margin of the former is negative, that is, oil is not enough, to have a solution, then the oil content should be positive, at this time may have a solution, we have to do is to find this point as a starting point, and then verify it; Then obviously you can directly select the front point as the starting point, and if the whole paragraph is negative, then no solution. */     Public intCancompletecircuit (int[] Gas,int[] cost) {                intI=0; intLeft=0; intBeg=0; intTotal=0;  while(i<gas.length) { Left+=gas[i]-Cost[i]; Total+=gas[i]-cost[i];//total in order to verify that the entire array is gas>cost            if(left<0) {Beg=i+1; Left=0; } I++; }        if(total>=0)returnBeg; Else return-1; }}

[Leedcode 134] Gas station

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.