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
- 题意为环形路段,测试能否从起始点i返回。
- i站点加油量为gas[i],到下一路段耗油量为cost[i]。
要解这道题目首先要知道一个结论:
如果一个数组的总和非负,那么一定可以找到一个起始位置,从他开始绕数组一圈,累加和一直都是非负的。
也就是说我们只要保证total>0,那么这道题就一定有解。
如果从i站开始到p站点发现邮箱空了,那么从i到p之间的所有站点都不用考虑,因为i肯定是正积累,除去i积累的那一站更不可能走通,同理之后i+1到p之间都不可能。
因此从p站开始start(也就是下面代码中遍历到i站start)。
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
if(gas.size() == 0 || cost.size() == 0 || gas.size() != cost.size()) return -1;
int total = 0, sum = 0, start = 0;
for(int i = 0; i < gas.size(); i++){
total += (gas[i] - cost[i]);
if(sum < 0){ //发现油箱空了,从下一个站点尝试
sum = (gas[i] - cost[i]);
start = i;
}else
sum += (gas[i] - cost[i]);
}
return total < 0 ? -1 : start; //用total判断start 是否是满足要求的解
}
};