首页 > 代码库 > Leetcode: Gas Station

Leetcode: 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.

难度:60.这道题用Brute Force的方法解比较好想,就是从每一个站开始,一直走一圈,累加过程中的净余的油量,看它是不是有出现负的,如果有则失败,从下一个站开始重新再走一圈;如果没有负的出现,则这个站可以作为起始点,成功。可以看出每次需要扫描一圈,对每个站都要做一次扫描,所以时间复杂度是O(n^2)。

 1 public class Solution { 2     public int canCompleteCircuit(int[] gas, int[] cost) { 3         int N = gas.length; 4         int[] balance = new int[N]; 5         for (int i = 0; i < N; i++) { 6             balance[i] = gas[i] - cost[i]; 7         } 8          9         for (int k = 0; k < N; k++) {10             if (check(balance, k, N) == 1) return k;11         }12         return -1;13     }14     15     public int check(int[] balance, int k, int N) {16         int sum = 0;17         for (int j = 0; j < N; j++) {18             if (k + j < N) sum = sum + balance[k+j];19             else sum = sum + balance[k+j-N];20             if (sum < 0) return 0;21         }22         return 1;23     }24 }

别人有O(N)的方法,未深究,参见http://blog.csdn.net/linhuanmars/article/details/22706553

Leetcode: Gas Station