【题目】
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.
【题解】
最容易想到的解法是遍历数组gas和数组cost每个索引 i,即以索引 i 为起点,将后面的数(gas[j] - cost[j])相加(循环回到 i ),如果最后得到的结果nTotal大于0,证明车从索引 i 开始可以循环一圈,时间复杂度为O(n^2)。
以上是我很愚蠢的想法,在参考了网上大神的思路后,发觉可以将复杂度降为O(n),很惭愧,真的很简单,在这里我就不重复这位大神的思路了,需要的话可以参考点击打开链接
【代码】
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int gasSize = gas.size();
int costSize = cost.size();
if (gasSize == 0 || costSize == 0 || gasSize != costSize)
return -1;
int nTotal = 0;
int nBegin = 0;
int nSum = 0;
int nDiff = 0;
for (int i = 0; i < gasSize; i++) {
nDiff = gas[i] - cost[i];
nTotal += nDiff;
if (nSum < 0) {
nSum = nDiff;
nBegin = i;
}
else
nSum += nDiff;
}
if (nTotal < 0)
return -1;
return nBegin;
}