当前位置:网站首页>leetcode:871. 最低加油次数【以前pat做过 + 最大堆 +贪心】
leetcode:871. 最低加油次数【以前pat做过 + 最大堆 +贪心】
2022-07-03 00:46:00 【白速龙王的回眸】

分析
注意,加油站是沿途,所以target一定在所有加油站的右方
然后,油的效果是累计的,根跳跃游戏不一样,不能走一下贪心一下
要用一个大根堆维护之前的加油中最大的加油量来贪心
思想就是,走到某个地方,如果去到之后的油是负数,那么就找之前存着的加油站中的最大值加一下,计算一次
如果加完之前的所有都到不了就凉凉
然后把当前的加油站放入大根堆(奖励),并更新上一个点prev
注意,target是最后一个curr,也要算上去
Ac code
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
# 加油的效果是累计的
# 所以用大根堆,每次取最大的加油来贪心(大根堆)
# 如果取完还不能到目前点,返回-1
ans, nowFuel, prev, pq = 0, startFuel, 0, []
stations.sort()
n = len(stations)
# 多一个target的位置
# 沿途右加油站,所以target一定在最右边
for i in range(n + 1):
# 当前要去的位置
curr = stations[i][0] if i < n else target
nowFuel -= curr - prev
# 不够油的,贪心加油
while nowFuel < 0 and pq:
nowFuel += -heappop(pq)
ans += 1
# 加完开始去不到
if nowFuel < 0:
return -1
# 若能去到,放进大根堆
if i < n:
heappush(pq, -stations[i][1])
# 更新prev
prev = curr
return ans
总结
贪心 + 大根堆
非常classic
边栏推荐
- Tensorflow 2. Chapter 15 of X (keras) source code explanation: migration learning and fine tuning
- [daily training] 871 Minimum refueling times
- [AUTOSAR + IO Architecture]
- About qbytearray storage hexadecimal and hexadecimal conversion
- Foundations of data science is free to download
- 2022中国3D视觉企业(引导定位、分拣场景)厂商名单
- excel IF公式判断两列是否相同
- Problèmes de configuration lex & yacc & Bison & Flex
- 百度智能云牵头打造智能云综合标准化平台
- [AUTOSAR I overview]
猜你喜欢

研发一款国产ARM智能边缘计算网关需要什么

【AutoSAR 十二 模式管理】

FPGA - 7系列 FPGA内部结构之Clocking -04- 多区域时钟
![[AUTOSAR twelve mode management]](/img/42/292e3da3f5d488a1e8c10ea9bbfbab.png)
[AUTOSAR twelve mode management]
![[overview of AUTOSAR three RTE]](/img/6a/0df33beb42f165af77a17b5d8b01e2.png)
[overview of AUTOSAR three RTE]

Understanding and distinguishing of some noun concepts in adjustment / filtering

2022.2.14 resumption
![[love crash] neglected details of gibaro](/img/d6/baa4b5185ddaf88f3df71a94a87ee2.jpg)
[love crash] neglected details of gibaro

瑞萨RZ/G2L 处理器简介|框架图|功耗|原理图及硬件设计指南

基于ARM RK3568的红外热成像体温检测系统
随机推荐
leetcode-241:为运算表达式设计优先级
About qbytearray storage hexadecimal and hexadecimal conversion
Several cases of recursive processing organization
Key detection and sinusoidal signal output developed by Arduino
Vulkan performance and refinement
Extension of flutter
【AutoSAR 六 描述文件】
[AUTOSAR + IO Architecture]
Web2.0的巨头纷纷布局VC,Tiger DAO VC或成抵达Web3捷径
leetcode-934:最短的桥
比较版本号
【AutoSAR 十二 模式管理】
1.11 - 总线
Illustrated network: what is virtual router redundancy protocol VRRP?
[AUTOSAR XIII NVM]
Initial order of pointer (basic)
【爱死机】《吉巴罗》被忽略的细节
【日常训练】871. 最低加油次数
The arm core board / development board of Feiling equipped with Ti am62x made its debut in embedded world 2022
Rust ownership (very important)