There are N gas stations along a circular route, where the amountof gas at station i isgas[i].
You have a car with an unlimited gas tank and it costscost[i]of gas totravel from station i to its next station (i+1). You begin thejourney with an empty tank at one of the gas stations.
Return the starting gas station's index if you can travel around thecircuit once, otherwise return -1.
Note:
The solution is guaranteed to be unique.
思路:上图为一个环形路,有6个加油站,假设从点1开到点2之后,开到点3的油量不够。也就是gas[1]-cost[1]+gas[2]-cost[2]<0。而此时ga1[1]+cost[1]必大于0(能从1到2)。也就是说gas[2]-cost[2]必小于0。记录此时1到3的油量sum=gas[1]-cost[1]+gas[2]-cost[2]。
所以新的起点应当从3开始。若想完成整个循环回到点3,则必须在到达点1之后的油量再加上之前记录的sum大于等于0,即可满足条件。
若新的起点为3,开到4之后,开到点5的油量不够,即
gas[3]-cost[3]+gas[4]-cost[4]<0。
更新sum为sum += gas[3]-cost[3]+gas[4]-cost[4]<0。也就是记录起点1到点5总的耗油量。然后以5为新起点,若想完成整个循环回到点5,则必须在到达点1之后的油量再加上之前记录的sum(1到5的)大于等于0,即可满足条件。
也就是说,不必一直循环,只需遍历到最后一个站点,再将其耗油到1后剩余的油量加上之前记录的sum,判断是否大于等于0,即可知道是否存在某个起点能够绕着环路跑一圈。
代码:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int start=0;
int length = gas.size();
int sum=0;
int tmp = 0;
for(int i=0; i!=length; i++)
{
sum += gas[i];
sum -= cost[i];
if(sum<0)
{
tmp += (sum);
start = (i+1)%length;
sum = 0;
}
}
if(sum+tmp >= 0)
return start;
else
return -1;
}