首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。