首页 > 其他 > 详细

LeetCode OJ - Gas Station

时间:2014-04-30 06:41:57      阅读:307      评论:0      收藏:0      [点我收藏+]

---恢复内容开始---

这道题考察的可能偏向逻辑的思考能力。

最有效的方法是时间复杂度为O(n),空间复杂度为O(1).这种高效算法,参考一个前辈的思想:“My linear solution based on a observation that, if you stops at certain gas station, the gas stations previous to the station you stop must not be a valid starting point. ”

意思是说从某个station开始,如果不能回到这个station,而是停在中间某一个station,那么从start到stop的这些station都不能作为汽车的起点。

下面是AC代码:

bubuko.com,布布扣
/**
     * 
     * @param gas
     * @param cost
     * @return Return the starting gas station‘s index if you can travel around
     *  the circuit once, otherwise return -1.
     */
    public int canCompleteCircuit(int[] gas, int[] cost)
    {
        int left = 0;
        int start=0, i;
        int N = gas.length;
        while(true)
        {
            i = start;
            left = 0;
            while(left+gas[i%N]-cost[i%N]>=0)
            {
                left = left+gas[i%N]-cost[i%N];
                i++;
                if(i%N == start%N)
                    return i%N;
            }
            if(i>N-1)
                return -1;
            start = ++i;    
        }
    }
bubuko.com,布布扣

 

---恢复内容结束---

LeetCode OJ - Gas Station,布布扣,bubuko.com

LeetCode OJ - Gas Station

原文:http://www.cnblogs.com/echoht/p/3690192.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!