思路:只要 loc < target
,代表还没到达(经过)目标位置,继续模拟行进过程。
每次将 remain
累加到 loc
中,含义为使用完剩余的油量,可以去到的最远距离,同时将所在位置 stations[idx][0] <= loc
的加油站数量加入优先队列(大根堆,根据油量从小到大排序)中。
再次检查是否满足 loc < target
(下次循环),此时由于清空了剩余油量 remain
,我们尝试从优先队列(大根堆)中取出过往油量最大的加油站并进行加油(同时对加油次数 res 进行加一操作)。
使用新的剩余油量 remain
重复上述过程,直到满足 loc >= target
或无油可加。
int minRefuelStops(int target, int startFuel, vector<vector<int>>& stations){
priority_queue<int>q;
int n=stations.size();
int index=0;
int fuel=startFuel,loc=0,res=0;
while(loc<target){
if(fuel==0){
if(!q.empty()){
fuel+=q.top();
res++;
q.pop();
}
else{
return -1;
}
}
loc+=fuel;
fuel=0;
while(index<n&&stations[index][0]<=loc){
q.push(stations[index][1]);
index++;
}
}
return res;
}