题目:在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。
你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。
如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/gas-station
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
An efficient approach is to use a Queue to store the current tour. We first enqueue first petrol pump to the queue, we keep enqueueing petrol pumps till we either complete the tour, or the current amount of petrol becomes negative. If the amount becomes negative, then we keep dequeuing petrol pumps until the queue becomes empty.
The amount of petrol that every petrol pump has.
Distance from that petrol pump to the next petrol pump.
思路:
用totalGas保存经过的加油站的所有汽油
用currentGas保存当前汽油。要是curretGas < 0的时候,重置currentGas.
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int len = gas.length;
int currentGas = 0;
int totalGas = 0;
int startStation = 0;
for(int i = 0; i < len; i++) {
currentGas += gas[i] - cost[i];
totalGas += gas[i] - cost[i];
if(currentGas < 0) {
currentGas = 0;
//i+1不影响,只是保存一个个变量而已
startStation = i + 1;
}
}
return totalGas >= 0? startStation : -1;
}
}