"Leetcode-Interview algorithm classic-java implementation" "134-gas Station (gas station problem)" __ Code

Source: Internet
Author: User
Tags diff
"134-gas Station (gas station problem) " leetcode-interview algorithm classic-java Implementation" "All topic Directory Index" Original title

There are N gas stations along a circular route, where the amount of gas in station I is gas[i].
You are have a car with the unlimited gas tank and it costs cost[i] of the gas to the 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 to the starting gas station ' s index if you can travel around the circuit once, otherwise return-1.
  Note:
The solution is guaranteed unique.
The main effect of the topic

Along the annular route there are N gas stations, of which the gas at the station I is the quantity is gas[i]. You have a car with an unlimited capacity of gas cans, from the gas station I to the next gas station site I+1, to consume cost[i] gases. When you start the journey, the gas tank is empty. Back to the index of the starting gas station, choose a starting point to travel, if you can travel round the circle once, return to the start of the gas station index, otherwise return-1.
  Note: The answer is guaranteed to be unique.
ideas for solving problems

Suppose from the site I start, to reach the site K, can still ensure that the oil tank did not see the bottom son, from the K after the end of the son. Then explain Diff[i] + diff[i+1] + ... + diff[k] < 0, while removing diff[k], the cumulative starting from Diff[i is >= 0. That is to say Diff[i] is also >= 0, this time we also need to try from site i + 1. Carefully think about it: if the car from the site I+1, arrived at the site K, and even not to the site K, the fuel tank to see the bottom son, because less add the site I oil ...
Therefore, when we found the K site to see the bottom of the mailbox, I to k these sites are not as a starting point to test, certainly do not meet the conditions, only need to try from the K+1 site. Thus, the time complexity of the solution is reduced from O (N2) to O (2n). The reason is O (2n), because the K+1 station as a predicate, the car has to circle back to K, to verify k+1 is satisfied.
Wait, do you really need this?
Let's simulate the process:
A. At the beginning, site 0 is predicate, assuming the car out of the site p, the fuel tank empty, assuming sum1 = diff[0] +diff[1 + ... + diff[p], know sum1 < 0;
B. According to the above discussion, we will p+1 as a predicate, out of Q station, the fuel tank is empty, set sum2 = Diff[p+1] +diff[p+2] + ... + diff[q], know sum2 < 0.
C. The q+1 as a predicate, assuming that the last station has been open to the end of the cycle, the fuel tank did not see the bottom son, set sum3 = Diff[q+1] +diff[q+2] + ... + diff[size-1], know sum3 >= 0.
To know whether the car can be opened back to Q Station, in fact, on the basis of SUM3, followed by 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 always remain non-negative, so we only calculate the SUM3 + sum1 whether <0, we know can drive to P+1 station.
If can from P+1 station, as long as calculate sum3 + sum1 + sum2 Whether < 0, know can not open back to Q station.
Because SUM1, sum2 are < 0, so if sum3 + sum1 + sum2 >=0 then sum3 + sum1 must >= 0, that is, as long as SUM3 + sum1 + sum2 >=0, the car must be able to open back to Q station. and sum3 + sum1 + sum2 is actually a diff array sum total, traversing all the elements have been counted out.
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 class Solution {public int cancompletecircuit (int[] gas, int[] cost) {//parameter check if (gas = = nul L | | Cost = NULL | | Gas.length = 0 | |
        Gas.length!= cost.length) {return-1;
        ///record access starting point int start = 0;
        The total difference of the added gas and the consumed gas is int sum = 0;

        Starting from the start position, add the gas and the total difference of the gas consumption int sum = 0;

            for (int i = 0; i < gas.length i++) {total + = (Gas[i]-cost[i]);
                If there is no oil in the tank if (sum < 0) {//Reset the oil in the tank = gas[i]-cost[i];
            Record the new start position start = i;
            else {//fuel tank also has oil, update oil tank in the number sum + = (Gas[i]-cost[i]); Return to total >= 0?
    Start:-1;  //The following method will timeout O (n^2) time complexity public int canCompleteCircuit2 (int[] gas, int[] cost) {//parameter check if (gas = = NULL | | Cost = NULL | | Gas.length = 0 | | Gas.length!= Cost. length) {return-1;
        //The remaining gas, starting at 0 int leftgas = 0;
        Start of the site int start = 0;

        Finished site int end = 1; Not gone one week while (Start < gas.length) {//The convenient amount of gas after reaching the next station Leftgas = Gas[start]-Cost[star

            T];

                You can walk to the next station if (Leftgas > 0) {//record the next station end = (start + 1)% Gas.length; If you continue to operate until the next station (Start!= end && (Leftgas + = (gas[end)-cost[end)) &
                gt;= 0) {end = (end + 1)% Gas.length;
                The//description has been traversed for a week if (start = =) {return start;
        }} start++;
    } return-1;
 }
}
Evaluation Results

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

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

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.