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.
加油站问题,每个加油站可以加的油给出来,从当前当下一个加油站会消耗的汽油量给出来了,求从哪个站点出发可以循环加油站一圈。
一开始是用一个二重循环的,这样复杂度为N^2,一直TLE,代码如下:
1 class Solution { 2 public: 3 int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { 4 for(int i = 0; i < gas.size(); ++i){ 5 int j = i; 6 int curGas = gas[j]; 7 while(curGas >= cost[j]){ 8 curGas -= cost[j]; 9 j = (j+1)%gas.size(); 10 curGas += gas[j]; 11 if(j == i) 12 return i; 13 } 14 } 15 return -1; 16 } 17 };
那只能使用其他方法了,可以看出维护一个部分差的和,如果前面的部分差的和一旦小于0的话,那么可以肯定的是应该在当前节点的下一处开始,然后在维护一个整体的和,当检查部分和可以完成时,查看整体差值是否小于0就可以了,代码如下所示:
1 class Solution { 2 public: 3 int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { 4 int totalLeft = 0; 5 int sum = 0; 6 int j = -1; 7 for(int i = 0; i < gas.size(); ++i){ 8 totalLeft += gas[i] - cost[i]; 9 sum += gas[i] - cost[i]; 10 if(sum < 0){ 11 j = i; 12 sum = 0; 13 } 14 } 15 if(totalLeft < 0) 16 return -1; 17 return j + 1; 18 } 19 };