当前位置:网站首页>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
边栏推荐
- [AUTOSAR twelve mode management]
- [AUTOSAR + IO Architecture]
- Meaning of Tencent cloud free SSL certificate extension file
- Matlab saves the digital matrix as geospatial data, and the display subscript index must be of positive integer type or logical type. Solve the problem
- Kubernetes resource object introduction and common commands (V) - (NFS & PV & PVC)
- 全志A40i/T3如何通过SPI转CAN
- Leetcode-1964: find the longest effective obstacle race route to each position
- 【案例分享】让新时代教育发展与“数”俱进
- File operation io-part2
- mysql 多表联合删除
猜你喜欢
1.11 - bus
2022.2.14 resumption
RISA rz/g2l processor introduction | frame diagram | power consumption | schematic diagram and hardware design guide
[AUTOSAR 11 communication related mechanism]
excel IF公式判断两列是否相同
【AutoSAR 十一 通信相关机制】
合并K个已排序的链表
[applet project development -- JD mall] user defined search component of uni app (middle) -- search suggestions
【AutoSAR 五 方法论】
(C语言)数据的存储
随机推荐
2022.2.14 resumption
[AUTOSAR five methodology]
465. 最优账单平衡 DFS 回溯
【AutoSAR 一 概述】
【AutoSAR 六 描述文件】
【案例分享】让新时代教育发展与“数”俱进
Set up nacos2 X cluster steps and problems encountered
瑞萨RZ/G2L ARM开发板存储读写速度与网络实测
递归处理组织的几种情况
Leetcode-2280: represents the minimum number of line segments of a line graph
[applet project development -- JD mall] user defined search component of uni app (middle) -- search suggestions
leetcode-2115:从给定原材料中找到所有可以做出的菜
解决ReactNative使用webView存在缓存问题
Lex & yacc & bison & flex configuration problems
Extension of flutter
飞凌搭载TI AM62x的ARM核心板/开发板首发上市,亮相Embedded World 2022
[AUTOSAR nine c/s principle Architecture]
How to convert Quanzhi a40i/t3 to can through SPI
Infrared thermography temperature detection system based on arm rk3568
【AutoSAR 七 工具链简介】