题目描述
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.
思路:
环状的加油站路径如果sum(gas[i])>sum(cost[i])则必定是有解的,基本思路是用两个变量,cur和total分别表示当前的油量和总共会剩余油量,如果在某一点cur小于0则说明前面几个站不可能作为起点,则起始站pos变为i+1,最终遍历完之后检查total是否大于0,是的话起点站就为pos,否则就为-1*。
代码:
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int total = 0,cur = 0, pos = 0;
for (int i=0; i<gas.length; i++){
total += gas[i] - cost[i];
cur += gas[i] - cost[i];
if (cur < 0){
cur = 0;
pos = i + 1;
}
}
return total >= 0 ? pos : -1;
}
}
网友评论