当前位置:网站首页>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++;
}
}
}
边栏推荐
- C language student management system based on linked list, super detailed
- 22-05-26 Xi'an interview question (01) preparation
- TP5 order multi condition sort
- Facial expression recognition based on pytorch convolution -- graduation project
- 【Rust 笔记】12-闭包
- Graphics_ Games101/202 learning notes
- 树形DP AcWing 285. 没有上司的舞会
- producer consumer problem
- 数位统计DP AcWing 338. 计数问题
- 请求参数的发送和接收
猜你喜欢
[rust notes] 02 ownership
Phpstudy 80 port occupied W10 system
Monotonic stack -42 Connect rainwater
Alibaba canal actual combat
单调栈-84. 柱状图中最大的矩形
樹形DP AcWing 285. 沒有上司的舞會
PHP uses foreach to get a value in a two-dimensional associative array (with instances)
Deep parsing (picture and text) JVM garbage collector (II)
Markdown learning
Message queue for interprocess communication
随机推荐
Common DOS commands
Slice and index of array with data type
树形DP AcWing 285. 没有上司的舞会
分配异常的servlet
Solution of 300ms delay of mobile phone
JS ternary operator - learning notes (with cases)
Six dimensional space (C language)
[rust notes] 09- special types and generics
Parameters of convolutional neural network
【Rust笔记】06-包和模块
Unity editor expansion - scrolling list
Downward compatibility and upward compatibility
I made mistakes that junior programmers all over the world would make, and I also made mistakes that I shouldn't have made
php public private protected
Message queue for interprocess communication
Drawing maze EasyX library with recursive backtracking method
MySQL index types B-tree and hash
[rust notes] 11 practical features
20220630学习打卡
UE4 source code reading_ Mobile synchronization