当前位置:网站首页>LeetCode 871. 最低加油次数
LeetCode 871. 最低加油次数
2022-07-03 08:49:00 【Sasakihaise_】

【贪心+优先队列】把当前油量能到达的加油站全部加入到优先队列中,按照加油量进行排序,如果当前不能到达终点,就把队列中最大的油加上,然后继续把找加完油之后能到达的加油站加入队列,如果最后队列为空还没能达到终点就返回-1.
以样例3为:
target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
1.最初有10,能到达的只有[10, 60],把他加入队列。
2.由于当前只行驶到10,还不到100,因此需要中途加油,将队列中的60拿出来加油,此时可以行驶到70,于是把后面70之前的加油站都加入队列,并按照油量排序后为:[60, 40], [20, 30], [30, 30]
3.当前行驶了70,需要继续加油,取出队列中最大的40,加完后总里程为110可到达终点。
贪心的精髓在于,在当前油量能到达的加油站中尽可能选择油量高的加油站加油。
class Solution {
// 贪心 找能到达的加油站中加的最多的
public int minRefuelStops(int target, int startFuel, int[][] stations) {
int sum = startFuel;
PriorityQueue<int[]> queue = new PriorityQueue<int[]>((a, b) -> { return b[1] - a[1]; });
int i = 0, n = stations.length, ans = 0;
while (true) {
if (sum >= target) {
return ans;
}
for (; i < n; i++) {
if (stations[i][0] <= sum) {
queue.offer(stations[i]);
} else {
break;
}
}
if (queue.isEmpty()) {
return -1;
}
int[] top = queue.poll();
sum += top[1];
ans++;
}
}
}边栏推荐
- Find the combination number acwing 886 Find the combination number II
- 20220630学习打卡
- Character pyramid
- Life cycle of Servlet
- Mortgage Calculator
- file_ put_ contents
- 【Rust 笔记】11-实用特型
- The method for win10 system to enter the control panel is as follows:
- Allocation exception Servlet
- Gif remove blank frame frame number adjustment
猜你喜欢

Unity interactive water ripple post-treatment

Facial expression recognition based on pytorch convolution -- graduation project

22-06-28 西安 redis(02) 持久化机制、入门使用、事务控制、主从复制机制
![[MySQL] MySQL Performance Optimization Practice: introduction of database lock and index search principle](/img/b7/7bf2a4a9ab51364352aa5e0a196b6d.jpg)
[MySQL] MySQL Performance Optimization Practice: introduction of database lock and index search principle

How to use Jupiter notebook

Graphics_ Learnopongl learning notes

First Servlet

Redux - learning notes

记忆化搜索 AcWing 901. 滑雪
![[concurrent programming] concurrent tool class of thread](/img/16/2b4d2b3528b138304a1a3918773ecf.jpg)
[concurrent programming] concurrent tool class of thread
随机推荐
[concurrent programming] Table hopping and blocking queue
First Servlet
Campus lost and found platform based on SSM, source code, database script, project import and operation video tutorial, Thesis Writing Tutorial
Complex character + number pyramid
How to delete CSDN after sending a wrong blog? How to operate quickly
Concurrent programming (V) detailed explanation of atomic and unsafe magic classes
【Rust笔记】02-所有权
使用dlv分析golang进程cpu占用高问题
Unity editor expansion - draw lines
如何应对数仓资源不足导致的核心任务延迟
Sending and receiving of request parameters
MySQL index types B-tree and hash
Allocation exception Servlet
Binary tree sorting (C language, char type)
PHP function date (), y-m-d h:i:s in English case
JS non Boolean operation - learning notes
Location of package cache downloaded by unity packagemanager
MySQL three logs
Alibaba canaladmin deployment and canal cluster Ha Construction
[rust notes] 12 closure