Gas Station
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.
分析:
方法一:暴力方法,从i站出发,遍历所有的站到(i-1),计算gas和 与 cost和的差是否大于0。如果中间出现<0则不可达,重新计算从i+1开始到i。时间复杂度O(n^2)
代码:
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int leng=gas.size();
if(leng<1) return -1;
int lenc=cost.size();
if(lenc<1) return -1;
if(leng != lenc) return -1;
int i=0,j=0;
for(;i<leng;i++){
int dif=0; //记录从到目前为止剩余量与cost的差值
for(j=i;j<leng+i;j++){
int t=j;
if(t>=leng) t=t%leng;
dif=dif+gas[t]-cost[t];
if(dif < 0) break;//不可达
}
if(j==(leng+i)){ //find 保证只有一个解,无需继续搜下去
return i;
}
}
return -1;//i>=len
}
};
方法二:时间复杂度O(n),开辟O(n)的空间 remain[i]=gas[i]-cost[i] 表示从i站到下一个站可剩余的gas量。可旋转一圈,需要remain[i]>=0,并且后面的累加和也要>=0。
代码:
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int leng=gas.size();
if(leng<1) return -1;
int lenc=cost.size();
if(lenc<1) return -1;
if(leng != lenc) return -1;
vector<int> remain(leng,0);
int i=0;
for( i=0;i<leng;i++){//求remain的剩余量
remain[i]=gas[i]-cost[i];
}
int start=0;
int sum=0;
int total=0;
for(i=0;i<leng;i++){
total+=remain[i];//没有起点满足条件的时候
sum+=remain[i];
if(sum<0){
start=i+1;
sum=0;
}
}
if(total<0) return -1;
else return start;
}
};