1.原题
原题链接:LeetCode134
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.
2.分析
有N个加油站绕成一个环,第i个加油站可以加gas[i]的油,从第i个加油站到第i+1个加油站需要耗费cost[i]的油,初始时,汽车没有油,问选哪个加油站为起点可以保证汽车能够绕所有加油站一圈。
如果要满足汽车能够绕加油站一圈,最基本的条件就是:到第i个加油站的时候,当前汽车剩余的油加上该加油站可以加的油要不少于到下一个加油站路上耗费的油。即:
cur+gas[i]>=cost[i](1)
一个最简单的思路就是从第0个加油站,每个加油站为起点挨个试就好了,按照这个思路写了写发现超时。
顺着这个思路稍微改一改,其实不必每个加油站都试,比如说,以第0个加油站为起点时,假如到第4个加油站的时候不满足上述式子了,这个时候可以直接把起点设定到第4个加油站以后的第5个加油站,因为0~4之间的其他加油站为起点肯定也是不满足的。
那么时候满足条件,什么时候不满足条件?
把加油站组成的圈分为两部分:前半圈和后半圈。前半圈是你之前走过的不满足条件的路,走完前半圈剩余的油耗一定为负,而后半圈则是一直满足该条件时车中剩余油量(一定是个非负数),这样意味着更新起点的位置将圆划分前后半圈。
最后,前半圈剩余油量和后半圈剩余油量之和如果大于0,则说明有解,否则返回-1。
这里后半圈实际就是 起点start到第N-1号加油站 剩余的油量(非负)
这里前半圈实际就是 0号加油站到第(start-1)号加油站 剩余的油量(负)
代码
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int start = 0;
int cur = 0;
int pre = 0;
int i;
int N = gas.size();
for (i = 0; i < N; i++)
{
cur = cur + gas[i] - cost[i];
if (cur < 0)//更新起点
{
pre = pre + cur;//前半圈负总和
start = i + 1;
cur = 0;
}
}
if (cur + pre >= 0)//前后总和大于0
return start;
else
return -1;
}
};