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

Gas Station [leetcode] 的两种解法

时间:2014-10-09 01:33:38      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:leetcode

由于gas总量大于cost总量时,一定可以绕所有城市一圈。

第一种解法

假设一开始有足够的油,从位置i出发,到位置k时剩余的油量为L(i,k)。

对任意的k,L(i,k)根据i的不同,只相差常数。

我们只需要找到最小的L(0, k)对应的k,k+1为所求。

代码如下:

    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        int start = 0;
        int curGas = 0, minGas = 0, totalGas = 0;
        for (int i = 0; i < gas.size(); i++)
        {
            int temp = gas[i] - cost[i];
            curGas += temp;
            totalGas += temp;
            if (minGas > curGas)
            {
                start = i + 1;
                minGas = curGas;
            }
        }
        if (totalGas >= 0) return start % gas.size();
        else return -1;
    }

第二种解法

如果L(i,k) < 0,则从i和k之间所有的位置都不能到k

所以从k+1的位置从0开始找

    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        int start = 0;
        int curGas = 0, totalGas = 0;
        for (int i = 0; i < gas.size(); i++)
        {
            int temp = gas[i] - cost[i];
            curGas += temp;
            totalGas += temp;
            if (curGas < 0)
            {
                start = i + 1;
                curGas = 0;
            }
        }
        if (totalGas >= 0) return start % gas.size();
        else return -1;
    }


Gas Station [leetcode] 的两种解法

标签:leetcode

原文地址:http://blog.csdn.net/peerlessbloom/article/details/39907811

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