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.

 


可以将两个数组看作一个数组,benifit[i]=gas[i]-cost[i] 
即为每一段路净所得的油.

两个原则:1. 如果总benifit为负数,则无论如何都开不完一圈。

2. 如果从一个加油站i出发,开到加油站j所属路段的时候油耗尽,那么从i,j之间的任一个加油站出发都会在j路段或j之前路段耗尽油。

基于以上两个原则,需要一个变量total统计benifit, 需要一个下标start标记起始站,初始为0,需要一个变量tank记录油箱。一旦在过程中某个i处发现tank小于0,那么start标记为i+1,意味着从之前start到i之间的加油站都不能作为起始加油站。

最后,查看total是否小于0.如果是则返回-1,不是则返回start.

代码:

 1 public int canCompleteCircuit(int[] gas, int[] cost) {
 2         int tank = 0;
 3         int start = 0;
 4         int total = 0;
 5         for(int i=0;i<gas.length;i++)
 6         {
 7             total += gas[i]-cost[i];
 8             tank += gas[i]-cost[i];
 9             if(tank<0)
10             {
11                 start = i+1;
12                 tank=0;
13             }
14         }
15         return total>=0?start:-1;
16     }

 

posted on 2014-10-26 23:38  metalx  阅读(337)  评论(0编辑  收藏  举报