用AI赚第一桶💰低成本搭建一套AI赚钱工具,源码可二开。 广告
## 一.题目描述 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. 环形路线上有N个加油站,每个加油站有汽油`gas[i]`,从每个加油站到下一站消耗汽油`cost[i]`,问从哪个加油站出发能够回到起始点,如果都不能则返回-1,最后题目提到解是唯一的。 ## 二.题目分析 以下解法的时间复杂度为:`O(n)`,每个车站可加油量和每段距离的耗油量分别存放在`gas`和`cost`中,可以设置两个变量:`sum`用于判断当前是否有足够的油量走到下一个加油站,若`sum<0`,则需将出发车站前移一个车站;`remainingGas`用于记录车开完整个过程后的油量。最终,判断`remainingGas` 是否大于零,是则返回初始车站的下标;若所有车站都出发都无法走完全程,则返回`-1`。 ## 三.示例代码 ~~~ #include <vector> using namespace std; class Solution { public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int remainingGas = 0; int resultIndex = 0; int sum = 0; for (size_t i = 0; i < gas.size(); ++i) // 对每个车站的情况进行遍历 { remainingGas += gas[i] - cost[i]; sum += gas[i] - cost[i]; if (sum < 0) { sum = 0; resultIndex = i + 1; } } if (remainingGas < 0) return -1; // 所有加油站的加油量小于消耗量 else return resultIndex; // 有解 } }; ~~~ 几个处理结果: ![](https://box.kancloud.cn/2016-01-05_568bb5ebdf980.jpg) ![](https://box.kancloud.cn/2016-01-05_568bb5ebec2ed.jpg) ![](https://box.kancloud.cn/2016-01-05_568bb5ec04ef8.jpg) ## 四.小结 该题是比较有趣的一题,该方法只是多种方法中一种。