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.
方法一:直接暴力破解,枚举以每个加油站为起点,时间复杂度为O(n2),空间复杂度为O(1)
方法二:由于车开始时是空油箱而且是无限空间,故其每到一个加油站必加满油,如果油箱内油够到下一个加油站,那就可以继续前行。故我们可以构造一个差值数组。
gas[0] | gas[1] | gas[2] | gas[3] |
cost[0] | cost[1] | cost[2] | cost[3] |
remain[0] | remain[1] | remain[2] | remain[3] |
remain[i]表示从加油站i到加油站(i+1)%n车还剩多少油,要让车可以走一圈,那么必须从 j 加油站开始,j需要满足remain[j] >= 0 且 累加右面的remain元素的和都需要为非负值
1 class Solution { 2 public: 3 int canCompleteCircuit(vector &gas, vector &cost) { 4 vector remain(gas.size(), 0); 5 for(int i=0; i