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.
Have you met this question in a real interview?
思路一:每个节点走一遍,判断从当前节点能否回到自身
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int n=gas.size();
for(int i=0;i<gas.size();i++)
{
int curgas=0;
int curpos=i;
for(int k=0;k<gas.size();k++)
{
curgas +=gas[curpos];
curgas -= cost[curpos];
if(curgas>=0)
curpos=(curpos+1)%n;
else
break;
}
if(curgas>=0)
return i;
}
return -1;
}
};
时间复杂度O(n^2) Result: TLE
思路二:用一个数组dp[]来记录 gas[]-cost[]
dp[i]=gas[i]-cost[i]。如果dp[i]==0表示从节点i刚好走到i+1。如果
dp[i]>0表示从节点i走到i+1 gas还有结余。如果dp[i]<0,表示从节点i 不能走到i+1
对于得到的数组dp[],求连续的元素和最大,返回最大元素和的下标,注意数组当成循环数组。
思路三:
如果i节点最远能到达的节点时k,那么不能到达K+1节点及其以后的节点。
算法从节点0出发,假设最远能到达的节点是i,如果i是最后一个节点则return 0.否则,从i+1节点开始出发,计算最远能到达的节点。重复以上操作指导我们打到最后的节点。最后 出发的节点就是最后的结果。
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int n=gas.size();
int pre=0;
int cur=0;
int index=0;
for(int i=0;i<n;i++)
{
cur +=gas[i]-cost[i];
if(cur<0)
{
pre+=cur;
cur=0;
index=i+1;
}
}
if(cur+pre>=0)
return index;
else
return -1;
}
};