当前位置:网站首页>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] thread foundation and sharing between threads
- Unity Editor Extension - Outline
- Six dimensional space (C language)
- Solution of 300ms delay of mobile phone
- Graphics_ Learnopongl learning notes
- 22-06-27 Xian redis (01) commands for installing five common data types: redis and redis
- How to use Jupiter notebook
- [rust notes] 06 package and module
- Deeply understand the underlying data structure of MySQL index
- [public key cryptography] ECC elliptic cryptosystem (implementing ElGamal encryption method)
猜你喜欢

20220630学习打卡

Campus lost and found platform based on SSM, source code, database script, project import and operation video tutorial, Thesis Writing Tutorial

Visual Studio (VS) shortcut keys

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

Concurrent programming (III) detailed explanation of synchronized keyword

Allocation exception Servlet

PHP uses foreach to get a value in a two-dimensional associative array (with instances)

JS ternary operator - learning notes (with cases)

Unity Editor Extension - drag and drop

Arbre DP acwing 285. Un bal sans patron.
随机推荐
Arbre DP acwing 285. Un bal sans patron.
22-06-28 Xi'an redis (02) persistence mechanism, entry, transaction control, master-slave replication mechanism
Life cycle of Servlet
Downward compatibility and upward compatibility
数位统计DP AcWing 338. 计数问题
[rust notes] 07 structure
Unity editor expansion - scrolling list
Gif remove blank frame frame number adjustment
[concurrent programming] Table hopping and blocking queue
Notes on understanding applets 2022/7/3
Unity learning notes
Concurrent programming (V) detailed explanation of atomic and unsafe magic classes
Dom4j遍历和更新XML
[rust notes] 11 practical features
cres
createjs easeljs
单调栈-503. 下一个更大元素 II
C language file reading and writing
[rust notes] 02 ownership
Alibaba canal actual combat