首页 > 其他 > 详细

Gas Station——LeetCode

时间:2015-03-29 23:32:59      阅读:202      评论:0      收藏:0      [点我收藏+]

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.

题意大概是:有N个加油站围成一个圈,每个加油站的油量是gas[i],从第i个加油站开到第i+1个加油站需要耗费cost[i]油量,问是否有一个解使得从某个加油站开始跑一圈,有的话返回开始跑的加油站的index。

我的做法就是从0开始遍历,sum+=gas[i]-cost[i],一旦sum<0了,说明从当前到0的所有点都不可能了,然后从下一个开始,一旦跑完一圈发现sum都不小于0,那么就可以返回当前的index了,否则全部遍历一遍没有解就返回-1。

Talk is cheap>>

  public int canCompleteCircuit(int[] gas, int[] cost) {
        int res;
        for (int i = 0; i < gas.length; i++) {
            res = gas[i] - cost[i];
            if (res >= 0) {
                int pos = i;
                for (int j = pos + 1; j < gas.length + pos; j++) {
                    int index = j % gas.length;
                    res += gas[index] - cost[index];
                    if (res < 0) {
                        pos = -1;
                        i = j;
                        break;
                    }
                }
                if (pos >= 0)
                    return pos;
            }
        }
        return -1;
    }

 

Gas Station——LeetCode

原文:http://www.cnblogs.com/aboutblank/p/4376582.html

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