力扣 : 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;
    }
};
相关推荐
傻乐u兔1 分钟前
C语言进阶————指针3
c语言·开发语言
大江东去浪淘尽千古风流人物18 分钟前
【VLN】VLN(Vision-and-Language Navigation视觉语言导航)算法本质,范式难点及解决方向(1)
人工智能·python·算法
rainbow688941 分钟前
Linux文件描述符与重定向原理
c++
独好紫罗兰1 小时前
对python的再认识-基于数据结构进行-a003-列表-排序
开发语言·数据结构·python
wuhen_n1 小时前
JavaScript内置数据结构
开发语言·前端·javascript·数据结构
努力学算法的蒟蒻1 小时前
day79(2.7)——leetcode面试经典150
算法·leetcode·职场和发展
2401_841495641 小时前
【LeetCode刷题】二叉树的层序遍历
数据结构·python·算法·leetcode·二叉树··队列
AC赳赳老秦1 小时前
2026国产算力新周期:DeepSeek实战适配英伟达H200,引领大模型训练效率跃升
大数据·前端·人工智能·算法·tidb·memcache·deepseek
CodeSheep程序羊1 小时前
拼多多春节加班工资曝光,没几个敢给这个数的。
java·c语言·开发语言·c++·python·程序人生·职场和发展
独好紫罗兰1 小时前
对python的再认识-基于数据结构进行-a002-列表-列表推导式
开发语言·数据结构·python