Gas Station leetcode java

愛做飯的小瑩子發表於2014-08-03

題目

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.

 

題解

 網上搜到的解法。

 據說是Bloomberg的面試題。

 用兩個變數存+= gas[i] - cost[i]。一個幫助判斷當前這個點作為gas station的起點合不合適,一個幫助判斷總的需求是不是大於供給。如果總的需求大於供給那麼肯定是無解的,如果需求小於等於供給,就可以返回剛才找到的起始點。

 

程式碼如下:

 1     public int canCompleteCircuit(int[] gas, int[] cost) {
 2         if (gas==null|| cost==null||gas.length==0||cost.length==0||gas.length!=cost.length)
 3          return -1;
 4          
 5         int sum = 0;  
 6         int total = 0;  
 7         int index = 0;  
 8         for(int i = 0; i < gas.length; i++){  
 9             sum += gas[i]-cost[i];  
10             total += gas[i]-cost[i];  
11             if(sum < 0){  
12                 index=i+1; 
13                 sum = 0;   
14             } 
15         }  
16         if(total<0)
17             return -1;  
18         else
19             return index;  
20     }

 Reference:http://blog.csdn.net/lbyxiafei/article/details/12183461

相關文章