LeetCode刷题实战134:加油站
共 2600字,需浏览 6分钟
·
2020-12-26 11:11
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 in the clockwise direction, otherwise return -1.
Note:
If there exists a solution, it is guaranteed to be unique.
Both input arrays are non-empty and have the same length.
Each element in the input arrays is a non-negative integer.
题意
输入:
gas = [1,2,3,4,5]
cost = [3,4,5,1,2]
输出: 3
解释:
从 3 号加油站(索引为 3 处)出发,可获得 4 升汽油。此时油箱有 = 0 + 4 = 4 升汽油
开往 4 号加油站,此时油箱有 4 - 1 + 5 = 8 升汽油
开往 0 号加油站,此时油箱有 8 - 2 + 1 = 7 升汽油
开往 1 号加油站,此时油箱有 7 - 3 + 2 = 6 升汽油
开往 2 号加油站,此时油箱有 6 - 4 + 3 = 5 升汽油
开往 3 号加油站,你需要消耗 5 升汽油,正好足够你返回到 3 号加油站。
因此,3 可为起始索引。
解题
2*gas.length-1
,这样能保证我们以最后一个加油站为起点时也能继续验证。public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
// gas减去cost,得到净油值
for(int i = 0; i < cost.length; i++){
gas[i] -= cost[i];
}
int tank = 0, res = -1;
for(int i = 0; i < gas.length * 2 - 1; i++){
int idx = i % gas.length;
// 更新油箱
tank += gas[idx];
// 如果油箱为负,说明走不到下一个加油站
if(tank < 0){
res = idx + 1;
tank = 0;
}
}
// 如果起点在最后一个加油站之后,说明无解
return res >= gas.length ? -1 : res;
}
}