leetcode——Gas Station

来源:互联网 发布:域名和服务器的关系 编辑:程序博客网 时间:2024/06/07 02:13

题目:

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.

方法一:

cost:

1131221gas:

1223122假设从下标2开始,它的gas=2,cost=3;

此时left=2-3=-1,因此无法到达下标3;于是将起点从下标2向前挪一个,为下标1,则在之前left的基础上又增加了gas[1]-cost[1] = 1,left变为了0,表示可以到达下标3;

所以这个过程之后,起点为下标1,而能够到达的最远变成了循环一圈之后的下标1,即能够走完一圈。


上述方法总结一下:

1、不管从哪个点(假设 从S0开始)作为起点,只要能走就往下走,直到走完n个站点,或者走不完一整圈(假设走到S),则将起点向前推进一个;

2、加上这个新起点的剩余值,看是否够到达上一次的终点S。

3、若不够,继续起点向前退一个;若够,则继续从S往下走,直到走完了所有n个站点,或者再走不下去,回到步骤1继续计算。

4、当走完了n个点之后,如果left总体还是小于0,则一定无法走完这一圈;如果left不小于0,则返回当前的起点下标。

注意,在步骤2中,如果在起点向前退一个的时候,所新加的这个起点的gas-station为负时,到S的left也要加上这个负值,从而更小。如果left最终小于0,则意味着连S都到不了。因此什么时候起点向前走的过程中,余下的气体量能够补上这个负值(该值会随着每次起点的变化而变化),什么时候才可能将最远点向更远推进。

复杂度:O(n)


AC代码(方法一):

public int canCompleteCircuit(int[] gas, int[] cost) {        int begin=0,end=0;        int count= gas.length;        int n=0;        int left = 0;        int current = begin;        while(n<count){            left += gas[current]-cost[current];            if(left>=0){                end++;                current=end;            }            else{                begin--;                if(begin<0)                    begin=count-1;                current = begin;            }            n++;        }        if(left>=0)            return begin;        else            return -1;    }

方法二:

该方法是在一的基础上衍生而来。在方法一中,起点向前退的时候有可能造成原先能够到达的S,反而最终到不了。这就说明,在a,b,c,d,e,f代表的站台中,如果以b为起点,能够最远到达d,那么不用再从c作为起点开始计算,因为如果b到不了e,那么c、d为起点也一定不能到e。则直接从e作为起点开始下一轮的计算即可。

上述现象的证明读者如果有兴趣可以自己试试,很有趣。

同样,该复杂度依然是O(n)。


0 0