"Leetcode-Interview algorithm classic-java implementation" "134-gas Station (gas stations problem)"

Source: Internet
Author: User

"134-gas station.""leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"Original Question

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 cost[i] of the gas-to-travel from station 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.

Main Topic

Along the annular route there are N gas stations, where the gas at station I is the amount of gas[i]. You have a gas tank with unlimited capacity, from gas station I to the next gas station site I+1, to consume cost[i] gas. When you start your journey, the gas tank is empty. Back to the starting gas station index, select a starting point to start the tour, if you can travel around in circles once, return to the starting gas station index, otherwise return-1.
  Note: The answer is guaranteed to be unique.

Thinking of solving problems

Suppose from the site I start, arrive at the site K, still can ensure that the oil in the tank did not see the bottom, starting from the K, see the bottom son. Then the diff[i] + diff[i+1] + ... + diff[k] < 0, and the addition of diff[k], the accumulation from diff[i] is >= 0. That is to say Diff[i] is also >= 0, this time we still need to try from site i + 1? Carefully think about: if the car from the site i+1 departure, arrived at the site K, even not to the site K, the tank on the bottom, because less add the site I oil ...
Therefore, when we found that reached the K site mailbox at the bottom, I to k these sites are not used as a starting point to test, certainly do not meet the conditions, only need to try from the K+1 site! Thus the solution time complexity is reduced from O (N2) to O (2n). The reason is O (2n), because the K+1 station as the start, the car has to circle back to K, to verify that the k+1 is satisfied.
Wait, do you really need this?
Let's simulate the process:
A. At the beginning, site 0 is the starting station, assuming the car out of the site p, the fuel tank is empty, assuming sum1 = Diff[0] +diff[1] + ... + diff[p], sum1 < 0;
B. According to the above discussion, we will p+1 as the departure point, open the Q station, the fuel tank is empty, set sum2 = Diff[p+1] +diff[p+2] + ... + diff[q], sum2 < 0.
C. Take q+1 as the start of the station, assuming that it has been open to the last stop, not the bottom of the tank, set sum3 = Diff[q+1] +diff[q+2] + ... + diff[size-1], the sum3 >= 0.
To know whether the car can drive back to Q station, in fact, on the basis of sum3, and then add diff[0] to diff[q], to see if sum3 in this process will be less than 0. But we have known diff[0] to diff[p-1] This section of the road, the fuel tank can remain non-negative, so we just calculate sum3 + sum1 Whether <0, know can open to P+1 station.
If can from P+1 station, as long as calculate sum3 + sum1 + sum2 Whether < 0, know can not open back Q station.
Because SUM1, sum2 are < 0, so if sum3 + sum1 + sum2 >=0 then sum3 + sum1 necessarily >= 0, that is, as long as SUM3 + sum1 + sum2 >=0, the car must be able to open the Q station. and sum3 + sum1 + sum2 is actually the sum total of the diff array, and all the elements have been counted.
So total can >= 0, is the existence of such a site sufficient and necessary conditions.
Thus the time complexity is further reduced from O (2n) to O (n).

Code Implementation

Algorithm implementation class

 Public classSolution { Public int Cancompletecircuit(int[] Gas,int[] cost) {//parameter checking        if(Gas = =NULL|| Cost = =NULL|| Gas.length = =0|| Gas.length! = cost.length) {return-1; }//Record The starting point of access        intStart =0;//Added gas and the total difference of the gas consumed        intTotal =0;//Starting from the start position, the total difference between the added gas and the consumed gas        intsum =0; for(inti =0; i < gas.length; i++) {Total + = (Gas[i]-cost[i]);//If the tank is out of oil            if(Sum <0) {//re-set the oil in the tanksum = gas[i]-cost[i];//Record a new start locationstart = i; }Else{//Oil in the tank, update the oil in the tankSum + = (Gas[i]-cost[i]); }        }returnTotal >=0? Start:-1; }//The following method will timeout O (n^2) time complexity     Public int CanCompleteCircuit2(int[] Gas,int[] cost) {//parameter checking        if(Gas = =NULL|| Cost = =NULL|| Gas.length = =0|| Gas.length! = cost.length) {return-1; }//The remaining gas, starting at 0        intLeftgas =0;//start of site        intStart =0;//End of site        intEnd =1;//Not a week away         while(Start < Gas.length) {//The gas is easy to reach after the next stationLeftgas = Gas[start]-Cost[start];//can go to the next station            if(Leftgas >0) {//Record the next stationEnd = (Start +1)% Gas.length;//Continuous operation if you can continue to the next station                 while(Start! = End && (Leftgas + = (Gas[end]-cost[end])) >=0) {end = (end +1)% Gas.length; }//Description has been traversed for a week                if(start = = end) {returnStart        }} start++; }return-1; }}
Evaluation Results

  Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.

Special InstructionsWelcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47678215"

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Leetcode-Interview algorithm classic-java implementation" "134-gas Station (gas stations problem)"

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.