题目
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 in the clockwise direction, otherwise return -1
.
Note:
- If there exists a solution, it is guaranteed to be unique.
- Both input arrays are non-empty and have the same length.
- Each element in the input arrays is a non-negative integer.
Example 1:
Input:
gas = [1,2,3,4,5]
cost = [3,4,5,1,2]
Output: 3
Explanation:
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.
Example 2:
Input:
gas = [2,3,4]
cost = [3,4,3]
Output: -1
Explanation:
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.
Solution
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int sum = 0;
int n = gas.size();
for (int i = 0; i < n; i++) {
sum += gas[i] - cost[i];
}
if (sum < 0) return -1;
int start = 0;
int leftGas = 0;
for (int i = 0; i < n; i++) {
leftGas += gas[i] - cost[i];
if (leftGas < 0) {
start = i + 1;
leftGas = 0;
}
}
return start;
}
};
题解
个人觉得这道题的解法是不太好理解的,至少我是这样的……大概是我现在太菜了吧……想了很久终于明白了
首先我们判断一下,gas
的总量够不够我们cost
的,如果不够,那么return -1
。
然后主体部分的大致思路是这样的:
- 首先我们设置开始点为
start = 0
,当前剩余的油量为leftGas = 0
- 然后计算从
start
开始时,我们依次预计到达下一站时剩余的油量(leftGas = leftGas + (gas[i] - cost[i])
) - 如果:
leftGas<0
,那么说明当前无法到达下一站,设置start = i + 1;
开始点为下一个站,leftGas = 0;
剩余油量设为0,重新开始计算。
可以写成伪代码的形式
start = 0, leftGas = 0, n = size of gas
for i from 0 to n:
if 油量不能到达下一站 then
开始点 start 设置为下一个点
剩余油量 leftGas 设置为 0
end if
end for
可能有人要问了,那我们每次都要跳过start
到i
之间的点吗,这些点里就没有我们所要的答案吗?
我们可以想象,假如我们在点i
之前失败了,那么也就是说
start
无法到达点i
.------> 1
- 但是可以到达
i
之前的任意一个点 。-------> 2
如果说这里边存在我们所需的答案的话,也就是说
- 其中存在
start < r <= i
,使得r
可以到达任意一个点。--------> 3
也就是说,我们可以构造一个路径 start --> r --> i
(根据2
和3
),使得 start --> i
,这和1
是矛盾的。
所以,我们可以确定,在start
到 i
的范围内,没有我们想要的答案,所以我们把start = i + 1
,依然是遍历了所有可能结果,只是跳过了一部分不可能的结果。
分析
时间复杂度: O(n),很明显了,就一次for
循环;
空间复杂度: O(1),这个解法里声明了4个整型变量,不会更多了,还可以更少,所以是O(1)的复杂度。