标签:
题目:
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.
这个题,一上来就想用穷举法做了。做法是,以每一个点作为起点,都试一次。复杂度O(n^2)。这个。。。不大好。其实我们重复计算了很多。
比如,我们以 a 为起点,试图走 a + 1, a + 2,a + 3 ... 一直走到b。如果我们在计算过程中发现,a 根本到不了b。按照原来的方法,我们该以 a + 1为起点,再算一次看能不能到b。
想想是不可能的。如果从a出发, 到a + 1点后,邮箱里有从a剩下的油(最不济刚好为空)。带着剩下的油都到不了b,你空着邮箱从头开始怎么可能。所以起点肯定不在a到b这段了。直接从b + 1开始算。
1 public int canCompleteCircuit(int[] gas, int[] cost) { 2 if (gas == null || cost == null || gas.length == 0 || cost.length == 0) { 3 return -1; 4 } 5 int start = 0; 6 int tank = 0; 7 int sum = 0; 8 for (int j = 0; j < gas.length; j++) { 9 int diff = gas[j] - cost[j]; 10 if (tank + diff >= 0) { 11 tank += diff; 12 }else{ 13 start = j + 1; 14 } 15 } 16 for (int i = 0; i < gas.length; i++) { 17 sum = sum + gas[i] - cost[i]; 18 } 19 if (sum >= 0) { 20 return start; 21 }else{ 22 return -1; 23 } 24 }
标签:
原文地址:http://www.cnblogs.com/gonuts/p/4418876.html