一、题目描述
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个加油站,第i个加油站有汽油量gas[i],从i加油站到i+1站需要消耗汽油cost[i],
问:从哪个加油站出发能够回到起始点,如果都不能则返回-1。
注意:解唯一。即每次输入相同数据输出的结果相同。
三、理解
一次遍历法思路:
车能开完全程需要满足两个条件:
1、车从i站能开到i+1。
2、所有站里的油总量要>=车子的总耗油量。
详细思路:
1.假设设定编号为1站为开始站点,如果油箱剩余油+i站点的油可以到达i+1站点,那么继续往下走。
2.否则,我们就要设定编号为i+1站点为新的开始站点。因为从旧开始站点到i+1不可达,那么从旧开始站点到i站点都不可以作为新开始站点。
3.从i+1到返回1站可达,站点总油量>站点总距离。那么i站点就是第一个符合条件的站。
图形描述:
从1开始,设定1为开始站点,1的油>1到2的距离,接着跑。
到2了,1剩余的油+2的油<2到3的距离, 设定3为开始站点,重置。
从3开始,3的油>3到4的距离,接着跑。
到4了,3剩余的油+4的油>4到1的距离。跑完了。
站点总油量>站点总距离,3就是第一个符合条件的站,返回3。(也许4也符合条件,这样算法可以保证解唯一)
问题:为啥3到1可以跑完,总油量>站点总距离,就可以说明从3可以跑完全程。
答:因为,开始站点(3)将当前路径分为A、B两部分。其中,必然有(1)A部分剩余油量<0。(2)B部分剩余油量>0。
所以,无论多少个站,都可以抽象为两个站点(A、B)。(1)从B站加满油出发,(2)开往A站,车加油,(3)再开回B站的过程。
重点:B剩余的油>=A缺少的总油。必然可以推出,B剩余的油>=A站点的每个子站点缺少的油。
此问题答案参考自:https://blog.csdn.net/zangdaiyang1991/article/details/89425686
最后代码解决问题:
public class Solution {
int canCompleteCircuit(int[] gas, int[] cost) {
int rest = 0, run = 0, start = 0;
for (int i = 0; i < gas.length; ++i){
run += (gas[i] - cost[i]);
rest += (gas[i] - cost[i]);
if (run < 0){
start = i + 1;
run = 0;
}
}
return rest < 0 ? -1: start;
}
}