问题
- 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.
思路:
- 尝试从每一个位置遍历一圈,跳过无效点
难点:
- 无效点的判断
分析:
- 如果 step != gas.size(),也就是说从当前的 start 位置开始没有转一圈:
- 首先对于 [start, start + step - 1] 之中的所有位置 pos,都有 left_gas[pos] >= 0
- 从 [start, start + step] 之中的任何点出发,都无法穿越 (start+step, start+step+1)
- 因此需要跳过其间所有点,从start + step + 1 开始重新尝试遍历
代码:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
for (int start = 0; start < gas.size();) { // 开始位置
int left_gas = 0; // 油箱余量
int step = 0; // 已经走过的步数
for (; step < gas.size(); ++step) {
int cur_pos = (start + step) % gas.size(); // 当前位置
left_gas += gas[cur_pos] - cost[cur_pos]; // 油箱余量更新
if (left_gas < 0) break; // 没油就挂掉
}
if (step == gas.size()) return start; // 找到一个可行的开始位置
start += step + 1; // 跳过无效步
}
return -1;
}
参考文献:
[1] http: //blog.csdn.net/kenden23/article/details/14106137