当前位置:网站首页>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++;
}
}
}边栏推荐
- Alibaba canaladmin deployment and canal cluster Ha Construction
- Try to reprint an article about CSDN reprint
- 【Rust笔记】05-错误处理
- PHP function date (), y-m-d h:i:s in English case
- Markdown learning
- Concurrent programming (VI) ABA problems and solutions under CAS
- Character pyramid
- [concurrent programming] concurrent security
- Dom4j traverses and updates XML
- 22-06-27 西安 redis(01) 安装redis、redis5种常见数据类型的命令
猜你喜欢

20220630学习打卡

【Rust笔记】02-所有权

樹形DP AcWing 285. 沒有上司的舞會

Alibaba canaladmin deployment and canal cluster Ha Construction

Binary tree sorting (C language, int type)

Arbre DP acwing 285. Un bal sans patron.

Mortgage Calculator

树形DP AcWing 285. 没有上司的舞会

UE4 source code reading_ Bone model and animation system_ Animation process

Debug debugging - Visual Studio 2022
随机推荐
DOM 渲染系统(render mount patch)响应式系统
LinkedList set
[redis] redis persistent RDB vs AOF (source code)
【Rust 笔记】08-枚举与模式
TP5 order multi condition sort
[concurrent programming] synchronization container, concurrent container, blocking queue, double ended queue and work secret
Unity multi open script
[rust notes] 11 practical features
单调栈-42. 接雨水
Six dimensional space (C language)
状态压缩DP AcWing 291. 蒙德里安的梦想
Find the intersection of line segments
The method for win10 system to enter the control panel is as follows:
记忆化搜索 AcWing 901. 滑雪
【Rust 笔记】12-闭包
Divide candy (circular queue)
22-05-26 西安 面试题(01)准备
[rust notes] 06 package and module
Dom4j traverses and updates XML
C language file reading and writing