当前位置:网站首页>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++;
}
}
}边栏推荐
- [linear table] basic operation of bidirectional linked list specify node exchange
- Phpstudy 80 port occupied W10 system
- 【Rust 笔记】11-实用特型
- Notes and bugs generated during the use of h:i:s and y-m-d
- 二进制转十进制,十进制转二进制
- Parameters of convolutional neural network
- On the difference and connection between find and select in TP5 framework
- Eating fruit
- 分配异常的servlet
- Animation_ IK overview
猜你喜欢

How to place the parameters of the controller in the view after encountering the input textarea tag in the TP framework

Parameters of convolutional neural network

Deep parsing (picture and text) JVM garbage collector (II)

Animation_ IK overview

求组合数 AcWing 886. 求组合数 II

Binary tree sorting (C language, char type)

Allocation exception Servlet

Log4j2 vulnerability recurrence and analysis

Unity learning notes

Gif remove blank frame frame number adjustment
随机推荐
Deep parsing (picture and text) JVM garbage collector (II)
[rust notes] 06 package and module
UE4 source code reading_ Bone model and animation system_ Animation compression
Servlet的生命周期
[concurrent programming] collaboration between threads
22-06-27 Xian redis (01) commands for installing five common data types: redis and redis
请求参数的发送和接收
Binary tree traversal (first order traversal. Output results according to first order, middle order, and last order)
【Rust 笔记】08-枚举与模式
Parameters of convolutional neural network
Campus lost and found platform based on SSM, source code, database script, project import and operation video tutorial, Thesis Writing Tutorial
【Rust 笔记】13-迭代器(上)
Sending and receiving of request parameters
[concurrent programming] working mechanism and type of thread pool
Dom4j traverses and updates XML
How to use Jupiter notebook
Tree DP acwing 285 A dance without a boss
[rust notes] 13 iterator (Part 1)
[rust notes] 07 structure
Unity Editor Extension - event handling