力扣 : 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;
    }
};
相关推荐
weixin_4461224628 分钟前
LinkedList剖析
算法
GiraKoo31 分钟前
【GiraKoo】C++14的新特性
c++
悠悠小茉莉41 分钟前
Win11 安装 Visual Studio(保姆教程 - 更新至2025.07)
c++·ide·vscode·python·visualstudio·visual studio
坏柠1 小时前
C++ Qt 基础教程:信号与槽机制详解及 QPushButton 实战
c++·qt
泽02021 小时前
C++之红黑树认识与实现
java·c++·rpc
百年孤独_2 小时前
LeetCode 算法题解:链表与二叉树相关问题 打打卡
算法·leetcode·链表
我爱C编程2 小时前
基于拓扑结构检测的LDPC稀疏校验矩阵高阶环检测算法matlab仿真
算法·matlab·矩阵·ldpc·环检测
算法_小学生2 小时前
LeetCode 75. 颜色分类(荷兰国旗问题)
算法·leetcode·职场和发展
运器1232 小时前
【一起来学AI大模型】算法核心:数组/哈希表/树/排序/动态规划(LeetCode精练)
开发语言·人工智能·python·算法·ai·散列表·ai编程
算法_小学生2 小时前
LeetCode 287. 寻找重复数(不修改数组 + O(1) 空间)
数据结构·算法·leetcode