[leetcode-134-Gas Station]

Posted hellowOOOrld

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode-134-Gas Station]相关的知识,希望对你有一定的参考价值。

There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1).
You begin the journey with an 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.

下边的超时了:

int canCompleteCircuit(vector<int>& gas, vector<int>& cost)
    {
        if (gas.size() != cost.size() || gas.size() == 0)return -1;

        int tank = 0;
        int num = gas.size();
        for (int i = 0; i < num;i++)
        {
            tank = 0;
            for (int j = i; j < num + i;j++)
            {
                tank += gas[j%num];
                tank -= cost[j%num];
                if (tank < 0)//不能到下一个station 重新开始
                {            
                    j = num+i;    //退出内层循环
                }
            }
            if (tank>=0)
            {
                return i;
            }
        }
        return -1;
    }

大牛的代码

先放这儿,回头细聊:

 int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        int i, j, n = gas.size();

        /*
         * If start from i, stop before station x -> no station k from i + 1 to x - 1 can reach x.
         * Bcoz if so, i can reach k and k can reach x, then i reaches x. Contradiction.
         * Thus i can jump directly to x instead of i + 1, bringing complexity from O(n^2) to O(n).
         */
        // start from station i
        for (i = 0; i < n; i += j) {
            int gas_left = 0;
            // forward j stations
            for (j = 1; j <= n; j++) {
                int k = (i + j - 1) % n;
                gas_left += gas[k] - cost[k];
                if (gas_left < 0)
                    break;
            }
            if (j > n)
                return i;
        }

        return -1;
    }

 

参考:

https://discuss.leetcode.com/topic/8860/fully-commented-o-n-c-solution-enabled-by-a-single-observation-of-mine






以上是关于[leetcode-134-Gas Station]的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-134-Gas Station

Leetcode 134 Gas Station

[leetcode-134-Gas Station]

[leetcode]134. Gas Station加油站

[LeetCode] 134. Gas Station

如何使用数组创建查找表