- class Solution {
- public:
- int canCompleteCircuit(vector<int>& gas, vector<int>& cost)
- {
- int curtotol = 0; // 当前累积油量
- int tatol = 0; // 总的油量减去总的花费油量
- int start = 0; // 起始加油站的索引
-
- // 遍历所有加油站
- for (int i = 0; i < gas.size(); i++)
- {
- curtotol += gas[i] - cost[i]; // 计算当前累积油量
- tatol += gas[i] - cost[i]; // 计算总的油量减去总的花费油量
-
- // 如果当前累积油量小于0,则无法到达下一个加油站
- if (curtotol < 0)
- {
- start = i + 1; // 重置起点为下一个加油站
- curtotol = 0; // 重置当前累积油量
- }
- }
-
- // 如果总的油量小于总的花费油量,则无法完成环路
- if (tatol < 0) return -1;
-
- // 返回起始加油站的索引
- return start;
- }
- };
tatol
小于总的花费油量,说明无论从哪个加油站出发都无法绕环路一周,直接返回 -1
。start
。假设 gas = [1, 2, 3, 4, 5]
和 cost = [3, 4, 5, 1, 2]
:
遍历加油站:
curtotol = 1 - 3 = -2
, tatol = -2
, start = 1
, curtotol = 0
curtotol = 2 - 4 = -2
, tatol = -4
, start = 2
, curtotol = 0
curtotol = 3 - 5 = -2
, tatol = -6
, start = 3
, curtotol = 0
curtotol = 4 - 1 = 3
, tatol = -3
curtotol = 5 - 2 = 6
, tatol = 0
最终 tatol >= 0
,返回 start = 3
。