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.
题目分析:
由于cost[i]代表的是从i到下一个节点i+1的燃油花费,因此也就是说该车只能够沿一个方向行进,要使得能够完成整个环形的行走,只需要确定从哪个节点出发,能够满足经过的每一个节点经过先加油再耗油后,油的剩余量为正。
首先考虑绝对不可能的情况,也就是所有节点的加油量加起来没有所有节点的耗油量的总和多,这种情况下无论选择在那个节点出发,都无法完成全程。
在满足总加油量大于总油耗的前提下,逐个考察每个节点。由于总加油量和总油耗一定,它们的差值,也就是完成全程后剩余的油是一个定值。随意挑选一个节点出发,如果全程的节点累计的剩余油量都大于0,那么明显符合。如果有负数,那么我们可以找到累计剩余油量最少的那个点,由于总量一定,那么从这个节点下一个节点开始到出发节点就是全程加油量最大的一段路程。因此考察从最小剩余量节点的下一个节点开始的路程,如果不满足就说明无法找到符合条件的出发点。
代码如下:
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int size(gas.size());
if(size == 0 || size != cost.size())
return -1;
vector<int> remain(size);
remain[0] = gas[0] - cost[0];
int min_remain(remain[0]), min_index(0);
// update the remain gas and find the min value
for(int i = 1; i < size; ++i) {
remain[i] = remain[i-1] + gas[i] - cost[i];
if(min_remain > remain[i]) {
min_remain = remain[i];
min_index = i;
}
}
// total gas is less than total cost
if(remain[size-1] < 0)
return -1;
return (min_index + 1) % size;
}
};