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.

这道题也挺麻烦的。乍看不难,用最简单的算法就是一个一个点地计算,计算到没油了,证明这点不能作为出发点。移动到下一个点作为出发点。这样的话思路还是挺简单的,不过这样写不accepted的,因为编译超时。

我觉得做这道题的关键是要可以总结出来这道题目的属性,注意Note这个地方,其属性主要有两个:

1 如果总的gas - cost小于零的话,那么没有解返回-1

2 如果前面所有的gas - cost加起来小于零,那么前面所有的点都不能作为出发点。

2013-12-1 update:

原创: 靖心http://write.blog.csdn.net/postedit/14106137

第一个属性的正确性很好理解。那么为什么第二个属性成立呢?

第二个属性表示到当前加油站首次为负,那么到前面加油站都是大于0的,如果从前面一个点开始,之前多余的油就用不上了,后面就还是负的,所以不可能从前面的点出发。

 

首先我们是从i =0个gas station计算起的,设开始剩油量为left=0,如果这个station的油是可以到达下一个station的,那么left=gas-cost为正数,

到了下一个station就有两种情况:

1 如果i=1个station的gas-cost也为正,那么前面的left加上当前station的剩油量也为正。

2 如果i=1个station的gas-cost为负,那么前面的left加上当前的station的剩油量也有两种情况:

一) left为正,那么可以继续到下一个station,重复前面计算i=2,i=3...,直到发生第二)种情况

 二)如果left为负,那么就不能到下一个station了,这个时候如果i=k(i<k<n),这个时候是否需要从第i=1个station开始重新计算呢?不需要,因为第k个station之前的所有left都为正的,到了第k个station才变成负。

 

 

主要利用属性2可以写程序:

程序一:记录最后一个加起来小于零的索引,然后返回这个索引+1就是答案了。

    public int canCompleteCircuit(int[] gas, int[] cost) {
        int sum=0;
        int total=0;
        int j=-1;
        for(int i=0;i<gas.length;i++){
            sum+=gas[i]-cost[i];
            total+=gas[i]-cost[i];
            if(sum<0){
                sum=0;
                j=i;//j用来记录出发点前一个
            }
        }
        if(total<0) return -1;
        else return j+1;
    }

 

程序2:传统的方法,依次将每一个加油站作为开始。

 public int canCompleteCircuit(int[] gas, int[] cost) {
        //依次从每个加油站开始,看能否回到这里
        for(int i=0;i<gas.length;i++){
            int j=i;
            int curgas=gas[j];
            while(curgas>=cost[j]){  //如果当前汽油能够到达下一站
                curgas-=cost[j];//剩余的天然气
                j=(j+1)%gas.length;//下一个站
                if(j==i) return i;//下一站回到出发点
                curgas+=gas[j];
            }
            
          
        }
          return -1;
    }

 

分类:

技术点:

相关文章: