[LeetCode 871]C++实现最低加油次数
汽车从起点出发驶向目的地,该目的地位于出发位置东面 target 英里处。
沿途有加油站,每个 station[i] 代表一个加油站,它位于出发位置东面 station[i][0] 英里处,并且有 station[i][1] 升汽油。
假设汽车油箱的容量是无限的,其中最初有 startFuel 升燃料。它每行驶 1 英里就会用掉 1 升汽油。
当汽车到达加油站时,它可能停下来加油,将所有汽油从加油站转移到汽车中。
为了到达目的地,汽车所必要的最低加油次数是多少?如果无法到达目的地,则返回 -1 。
注意:如果汽车到达加油站时剩余燃料为 0,它仍然可以在那里加油。如果汽车到达目的地时剩余燃料为 0,仍然认为它已经到达目的地。
示例 1:
输入:target = 1, startFuel = 1, stations = []
输出:0
解释:我们可以在不加油的情况下到达目的地。
示例 2:
输入:target = 100, startFuel = 1, stations = [[10,100]]
输出:-1
解释:我们无法抵达目的地,甚至无法到达第一个加油站。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-number-of-refueling-stops
方法:贪心
class Solution {
public:
int minRefuelStops(int target, int startFuel, vector<vector<int>>& stations) {
if(target<=startFuel)
return 0;
if(startFuel<target&& stations.size()==0)
return -1;
int max_target=startFuel;//能到达的最远位置
int count=0;//加油计数
int max_oil=0;//最大加油量
int temp=0;//最大加油量的加油站
int index=0;//遍历加油站
//思路:有油,一直走;没油,加上之前途经的最大油量
while(max_target<target){
//当有加油站,且所在位置小于当前位置
for(index=0;index<stations.size()&&stations[index][0]<=max_target;++index){
if(max_oil<stations[index][1]){
max_oil=stations[index][1];
temp=index;
}
}
stations[temp][1]=0;//加完油,加油站油量为空
if(max_oil==0)//没有加油站了
return -1;
max_target+=max_oil;
max_oil=0;
count++;
}
if(max_target>=target)
return count;
return -1;
}
};