题目:
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.
一个环路上有N个加油站,每个加油站的油量是 gas[ i ] 。假设你有一个无限制的油箱的车,从第 i 个加油站到 i + 1 个加油站需要消耗 cost[ i ] 的油量。在某个加油站开始你的旅行,但是油箱初始是空的。
如果可以绕着环路环形一周,那么返回起始加油站的位置,否则返回 -1 。
Note:
The solution is guaranteed to be unique.假定结果是唯一的。
思路:
1 如果总的gas – 总的cost小于零的话,那么肯定没有解,返回-1,反之,如果总的gas – 总的cost大于零,则肯定有解。
2 如果从0到达某一点 i 时所有的gas总和 < cost总和,说明0不能作为起始点,因为无法到达i。假设放弃0,从1开始,则1肯定也无法到达i,因为0能到达1说明gas[0]>=cost[0],这样从1到i的gas总和更<cost总和了,意思就是0点肯定是做贡献的(或者贡献为0),现在去掉这个贡献,1就更不能到达i了。同理可以得到从2到i-1所有的点都无法到达i,因此从0点到 i 点的所有的点都不能作为出发点。因此出发点肯定在后面,则从 i + 1 点开始对后面的数组判断。利用1 的结论,如果总和gas > 总的cost ,那么肯定存在解,解就是最后一个满足gas总和 > cost总和的点的后一个点。
代码:
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost)
{
int gap = 0;//当前点之前gas总和与cost总和的差
int totalSum = 0;//所有点的gas总和和cost总和的差
int result = 0;
for(int i = 0 ; i < gas.size() ; i++)
{
gap += gas[i] - cost[i];
totalSum += gas[i] - cost[i];
//如果当前gap小于0,则把result置为i+1,因为之前的gap>=0,现在gap< 0 说明gas[i] - cost[i]<0,因此当前i并不能到i+1,所以不能作为起点。
//并且把gap置为0,重新从i+1开始计算之后的gas总和和cost总和的差
if(gap < 0)
{
result = i + 1 ;
gap = 0;
}
}
//如果gas和较小,则无解
if(totalSum < 0)
return -1;
else
return result ;
}
};