力扣 : 871. 最低加油次数

871. 最低加油次数 - 力扣(LeetCode)

每次用优先队列保存每个加油站可以加的油 , 如果达不到下一个加油站或终点站时,就拿一个最大的加油 (保证答案次数最少,越大开的越远嘛)

注意随时判断对否到达了终点站!

cpp 复制代码
class Solution {
public:
    int minRefuelStops(int target, int startFuel, vector<vector<int>>& stations) {

        if(startFuel >= target)return 0;

        int ans=0;
        priority_queue<int> pq;  //放已经走过的加油站可以加的油

        for(auto i:stations)
        {
            if(i[0] > startFuel)
            {
                while(!pq.empty() && startFuel < i[0])
                {
                    startFuel += pq.top();
                    pq.pop();
                    ans++;
                    if(startFuel >= target)return ans;
                }

                if(startFuel < i[0])
                return -1;
            }

            pq.push(i[1]);

        }

        while(!pq.empty() && startFuel < target)
        {
            startFuel += pq.top();
            pq.pop();
            ans++;
            if(startFuel >= target)return ans;
        }

        if(startFuel < target)return -1;

        return ans;
    }
};
相关推荐
SNAKEpc121386 分钟前
QML和Qt Quick
c++·qt
hansang_IR16 分钟前
【题解】洛谷 P4286 [SHOI2008] 安全的航线 [递归分治]
c++·数学·算法·dfs·题解·向量·点积
乐迪信息16 分钟前
乐迪信息:AI摄像机在智慧煤矿人员安全与行为识别中的技术应用
大数据·人工智能·算法·安全·视觉检测
GanGuaGua24 分钟前
Linux系统:线程的互斥和安全
linux·运维·服务器·c语言·c++·安全
怀旧,33 分钟前
【C++】18. 红⿊树实现
开发语言·c++
lsnm33 分钟前
【LINUX网络】IP——网络层
linux·服务器·网络·c++·网络协议·tcp/ip
多恩Stone44 分钟前
【3DV 进阶-2】Hunyuan3D2.1 训练代码详细理解下-数据读取流程
人工智能·python·算法·3d·aigc
宁静致远20211 小时前
【C++设计模式】第三篇:观察者模式(别名:发布-订阅模式、模型-视图模式、源-监听器模式)
c++·观察者模式·设计模式
dragoooon341 小时前
[数据结构——lesson5.1链表的应用]
数据结构·链表
惯导马工2 小时前
【论文导读】IDOL: Inertial Deep Orientation-Estimation and Localization
深度学习·算法