当前位置:网站首页>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++;
}
}
}边栏推荐
- [concurrent programming] Table hopping and blocking queue
- Deeply understand the underlying data structure of MySQL index
- Notes and bugs generated during the use of h:i:s and y-m-d
- Analysis of Alibaba canal principle
- Parameters of convolutional neural network
- Character pyramid
- Unity Editor Extension - event handling
- Markdown learning
- 记忆化搜索 AcWing 901. 滑雪
- Try to reprint an article about CSDN reprint
猜你喜欢

Visual Studio (VS) shortcut keys

Find the combination number acwing 885 Find the combination number I
![[concurrent programming] thread foundation and sharing between threads](/img/26/60fbfe65b186867a3b1cb58d481226.jpg)
[concurrent programming] thread foundation and sharing between threads

数据库原理期末复习

Find the combination number acwing 886 Find the combination number II

Binary tree sorting (C language, int type)

Allocation exception Servlet

UE4 source code reading_ Bone model and animation system_ Animation process

Binary to decimal, decimal to binary

Deep parsing (picture and text) JVM garbage collector (II)
随机推荐
数据库原理期末复习
22-05-26 Xi'an interview question (01) preparation
Unity learning notes
How to use Jupiter notebook
Arbre DP acwing 285. Un bal sans patron.
Dom4j遍历和更新XML
22-06-27 Xian redis (01) commands for installing five common data types: redis and redis
[rust note] 10 operator overloading
TP5 order multi condition sort
树形DP AcWing 285. 没有上司的舞会
[rust notes] 02 ownership
【Rust笔记】05-错误处理
Debug debugging - Visual Studio 2022
注解简化配置与启动时加载
如何应对数仓资源不足导致的核心任务延迟
高斯消元 AcWing 883. 高斯消元解线性方程组
Annotations simplify configuration and loading at startup
Alibaba canaladmin deployment and canal cluster Ha Construction
URL backup 1
[linear table] basic operation of bidirectional linked list specify node exchange