# Leetcode "Gas Station"-to be revised

Source: Internet
Author: User

First I thought of a DP Solution... But TLE. So there must be a O (N). I thought of mono-queue... but looks too complex.

So what is the naive solution? O (N ^ 2) Of course. If we pick next start station smartly, we can make it linear: http://blog.csdn.net/kenden23/article/details/14106137

Smart idea... I need practice more and think more ....

`class Solution {public:    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {        size_t cnt = gas.size();        if (cnt == 1)        {            if (gas[0] >= cost[0]) return 0;            return -1;        }        for (int i = 0; i < cnt; i++)        {            int delta = 0;            int step;            bool bFound = true;            for (step = 0; step < cnt - 1; step++)            {                delta += gas[(i + step) % cnt] - cost[(i + step) % cnt];                if (delta < 0)                {                    i += step;                    bFound = false;                    break;                }            }            if (!bFound) continue;            if (delta > 0) return i;            else i += step - 1;        }        return -1;    }};`
Related Keywords:

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.