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.

思路:

1. 循环遍历每个起点,计算是否满足要求。时间复杂度为O(n^2);

2. 假设从i->j-1,剩余的汽油量都够行驶,而从j-1行驶到j时,汽油不够了,即从i开始无法行驶到j。

  此时,按照第1种思路,是从i+1作为新的起点开始遍历。

  但是在第i个加油站一定有gas[i] >= cost[i],则从i+1到j同样不能完成;

  并且gas[i]+gas[i+1]-cost[i]-cost[i+1] >= 0,则从i+2到j也不能完成;

  以此类推,i到j之间的所有点都不能完成要求,则直接从j+1作为新的节点开始遍历。

  当i到n满足条件时,需要判断i到j的剩余油量是否够0到i-1的路程使用。

代码如下:

public int canCompleteCircuit(int[] gas, int[] cost) { 
        int left = 0; // 汽油余量
        int missFromZeroToEnd = 0; // 从0到start的缺油量
        int start = 0;
         
        for (int i=0; i < gas.length; i++) {
            left = gas[i] - cost[i] + left;
            if (left < 0) {
                start = i + 1;
                missFromZeroToEnd = left + missFromZeroToEnd;
                left = 0;
            }
        }
         
        if (left + missFromZeroToEnd >= 0) {
            return start;
        }
        return - 1;
    }

 

posted on 2015-02-24 00:23  linxiong1991  阅读(118)  评论(0)    收藏  举报

导航