力扣 : 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;
    }
};
相关推荐
PAK向日葵6 小时前
【算法导论】PDD 0817笔试题题解
算法·面试
地平线开发者8 小时前
ReID/OSNet 算法模型量化转换实践
算法·自动驾驶
快乐的划水a8 小时前
组合模式及优化
c++·设计模式·组合模式
地平线开发者9 小时前
开发者说|EmbodiedGen:为具身智能打造可交互3D世界生成引擎
算法·自动驾驶
星星火柴93610 小时前
关于“双指针法“的总结
数据结构·c++·笔记·学习·算法
艾莉丝努力练剑11 小时前
【洛谷刷题】用C语言和C++做一些入门题,练习洛谷IDE模式:分支机构(一)
c语言·开发语言·数据结构·c++·学习·算法
闪电麦坤9512 小时前
数据结构:迭代方法(Iteration)实现树的遍历
数据结构·二叉树·
C++、Java和Python的菜鸟12 小时前
第六章 统计初步
算法·机器学习·概率论
Cx330❀12 小时前
【数据结构初阶】--排序(五):计数排序,排序算法复杂度对比和稳定性分析
c语言·数据结构·经验分享·笔记·算法·排序算法