【题目】
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.
【题意】
有N个节油站构成一个环状路径,每个加油张能够加油的量由gas[i]给出,车从i站驶到下一站i+1需要消耗的油量由cost[i]给出找出从那个加油站始发能够正好跑完一圈。返回加油站的索引位,如果找不到返回-1
题目保证,解是唯一的。
【思路】
1. 先计算要行驶到下一个加油站,每站至少需要剩油多少,即能够从当前节点可达下一站的临界条件2. 选择那些剩油需求<=0的加油站作为起点,依次判断
【代码】
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;
}
};