Leetcode (WU): 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.



Class Solution {public:    int. cancompletecircuit (vector<int>& gas, vector<int>& cost) {        int Length=gas.size ();    Vector<int> Tmpgas (length,0);        for (int i=0;i<length;++i)    {    tmpgas[i]=gas[i]-cost[i];//a new array of difference, representing the complement or consumption    }        int startindex=0 ;//initial starting point    int sum=tmpgas[startindex];        int i=0;    while (true)    {    i++;    if (i>=length)    {    i=i-length;    }        if (sum<0)    {    startindex=i;//one of the following nodes as the starting point    if (startindex==0)    return-1;//back to the initial starting point, the loop    begins to appear Sum=tmpgas[startindex];    }    else    {    sum+=tmpgas[i];
<span style= "White-space:pre" ></span>    //has reached the finish line to determine if the whole process can be successfully completed    if (startindex==0 && i== Length-1)    {//If the starting point is 0, the current node is also the last nodes    if (sum<0)    return-1;    else    return startIndex;    }        if (i==startindex-1)    {//If the current node is the last node of the loop if    (sum>=0)    return startIndex;    else return-1;}}}}    ;


Leetcode (WU): 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.