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.
一种做法是以每一个站为起点推断是否可以在行走一个周期后回到自身。
AC code:
class Solution { public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int res = 0, i = res, n = gas.size(), left = 0; while (res<n) { left = left + gas[i] - cost[i]; if (left<0) { res++; left = 0; i = res; } else { i = (++i) % n; if (i == res) return res; } } return -1; } };事实上还有更优化的方法。在推断以当前网站res为起始网站是否可以回到当前网站的过程中,假设在网站i出现不能到达i+1网站的情况,那么以从当前网站res到A直接的全部网站为起始点,都不能跨越过i~i+1这个坎。可以这样理解这句话。对于res~i之间的随意网站x,汽车从res出发到达x剩余的油量大于等于0,所以汽车从res出发到达i剩余的油量大于等于从网站x出发到达i剩余的油量。
基于上面的结论,能够知道。下一个可能的起始点就是i+1。我们直接让res等于i+1,再继续运行程序,直到res等于n,此时说明不存在满足条件的网站。
优化后的方法时间复杂度O(n)。
AC code:
class Solution { public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int res = 0, i = res, n = gas.size(), left = 0; while (res<n) { left = left + gas[i] - cost[i]; if (left<0) { if(i>res) res=i; else res++; left = 0; i = res; } else { i = (++i) % n; if (i == res) return res; } } return -1; } };