码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode-134-Gas Station]

时间:2017-03-01 00:36:20      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:amount   bsp   class   log   int   targe   不能   journey   start   

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]

标签:amount   bsp   class   log   int   targe   不能   journey   start   

原文地址:http://www.cnblogs.com/hellowooorld/p/6481637.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!