初始化起始车站begin和抵达车站end为0, 初始化记录车上还剩的汽油gas_in_car为0,迭代gas.size()次。每次迭代:
计算当前所在车站gas[now] - gas[cost], 将差值加入gas_in_car中
1) 当gas_in_car小于0时,说明无法从begin抵达end, 将begin前移(-- begin), 继续迭代
2) 当gas_in_car大于0时,说明可以从begin抵达end, 将end后移(++ end), 继续迭代
迭代gas.size()次后,无论怎样,我们已经把所有车站迭代完了,由于测试样例保证唯一解,所以最终
1) 要么我们已经找到了begin, 使得gas_in_car大于等于0
2) 要么经过gas.size()次迭代后得到的gas_in_car小于0, 此时返回-1即可。
代码:
class Solution
{
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost)
{
int gas_in_car = 0;
int begin = 0;
for (int now=0, end=0, station_cnt=0; station_cnt < gas.size(); ++ station_cnt)
{
gas_in_car = gas_in_car + gas[now] - cost[now];
if (gas_in_car < 0) // backward
{
-- begin;
begin = begin<0? gas.size()-1: begin;
now = begin;
} else // forward
{
++ end;
now = end;
}
}
return gas_in_car>=0? begin: -1;
}
};