There are N gas stations along a circular route, where the amount of gas at stationi isgas[i]
.
You have a car with an unlimited gas tank and it costscost[i]
of gas to travel from stationi 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.
题目链接:https://leetcode.com/problems/gas-station/
题目大意:有一个环形公路,路上有n个加油站,第i个加油站有gas[i]这么多油,从第i个加油站到第i+1个加油站需要消耗cost[i]的油,问从哪个加油站出发可以环绕行驶一周,保证答案唯一,不存在的情况下输出-1
题目分析:首先若所有加油站的总油量不比总消耗小,这种情况下解必然存在,从0位置开始,若到了某个加油站,这时候累计的油量小于消耗量了,那么显然前面的加油站都不能当做起点,因为上次我设定的起点肯定是油量大于消耗量的,往后的情况下累计油量小于消耗量了,说明这中间无论我取哪个作为起点,到当前这个加油站都会出现累积量小于消耗量的情况,因此就不断把起点设在不满足条件的点的后面那个点上,环形取个模即可。
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int len = gas.length;
int ans = 0;
int pos = 0;
int sumGas = 0, sumCost = 0;
int curGas = 0, curCost = 0;
while(pos < len) {
sumGas += gas[pos];
sumCost += cost[pos];
curGas += gas[pos];
curCost += cost[pos];
if(curGas < curCost) {
ans = (pos + 1) % len;
curGas = 0;
curCost = 0;
}
pos ++;
}
if(sumGas < sumCost) {
ans = -1;
}
return ans;
}
}