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.
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int size=gas.size();
if(size==0)return -1; //注意size=1也是需要考虑。这里好大一个坑,竟然真有自己驶到自己这种荒谬的case
vector<int> gasRemainNeed;
for(int i=0; i<size; i++){
gasRemainNeed.push_back(cost[i]-gas[i]);
}
int start=0;
int p=start;
int remain=0;
while(start<size){
while(remain>=gasRemainNeed[p%size]){ //判断当前汽车的剩油量够不够跑到下一站,如果能跑就不断跑下去,直到跑不下去为止
remain-=gasRemainNeed[p%size]; //计算驶到下一站的剩油量
p++; //游标指向下一站
if(p%size==start)return start; //如果已经跑完一圈,返回
}
//start向后移动,并不断更新油箱中的剩油,直到剩油量能使车从p驶到p+1
while(start<size && start<p && remain<gasRemainNeed[p%size]){
remain+=gasRemainNeed[start];
start++;
}
//如果p指针正好指到start上,则两个游标同时向后移动一位
if(start==p){start++; p++;}
}
return -1;
}
};LeetCode: Gas Station [134],布布扣,bubuko.com
原文地址:http://blog.csdn.net/harryhuang1990/article/details/34532657