题目大意:
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.
Note:
The solution is guaranteed to be unique.
意思就是:
在一条环型线路上有N个加油站,每个加油站的油的数量是gas[i]
。有一辆车,它有一个油箱可以装无限量的汽油,汽车从加油站i到下一个加油站i+1需要耗费cost[i]
的汽油。
问题是:该汽车汽油罐开始时是空的,如果该车能绕着环型线路走完,返回起始加油站的index;否则,返回-1。
注意:如果存在方案,该方案必定是唯一的。
解题思路:
1,存在一种暴力求解法。即从每个加油站开始都计算一次。看能不能到达终点,但是时间肯定超时。
2,较好的方法:任意选择一个加油站作为开始,一直往下走,如果到达某一站加的油减去耗费的油为负值,则选择截至的那个加油站的下一站作为起始站,继续计算 ; 直到计算完所有加油站为止。
最后需要检测一下选择的起始站,能否跑完全程。
代码如下:
class Solution { public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { vector<int>::size_type lenght_gas = gas.size(); int i = 0,surplus = 0,j,result = 0; while(i != lenght_gas){ //j = i; for(j = i;j<lenght_gas;j++){ surplus += gas[j] - cost[j]; if(surplus < 0 ){ i = j + 1; surplus = 0; break; } } if(j == lenght_gas){ result = i; break; } } surplus = 0; for(j=result;j<lenght_gas;j++){ surplus += gas[j] - cost[j]; } for(j = 0;j<result;j++){ surplus += gas[j] - cost[j]; } if(surplus < 0){ return -1; } else{ return result; } } };