当前位置:网站首页>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
边栏推荐
- [jetcache] jetcache configuration description and annotation attribute description
- Sentry developer contribution Guide - configure pycharm
- How to systematically learn machine learning
- Vulkan-性能及精细化
- Cordova plugin device obtains the device information plug-in, which causes Huawei to fail the audit
- 【小程序项目开发-- 京东商城】uni-app之自定义搜索组件(中)-- 搜索建议
- AEM: Nanlin fan Ben et al. - plant rhizosphere growth promoting bacteria control soybean blight
- Explain the basic concepts and five attributes of RDD in detail
- leetcode-849:到最近的人的最大距离
- 详解RDD基本概念、RDD五大属性
猜你喜欢
研发一款国产ARM智能边缘计算网关需要什么
[AUTOSAR 11 communication related mechanism]
[AUTOSAR twelve mode management]
[case sharing] let the development of education in the new era advance with "number"
Advanced pointer (I)
Lu Zhe, chief scientist of Shiping information: building data and personnel centered security capabilities
Rk3568 development board evaluation (II): development environment construction
【案例分享】让新时代教育发展与“数”俱进
Basic use of sringcloud & use of component Nacos
安全运营四要素之资产、脆弱性、威胁和事件
随机推荐
Leetcode 294. Flip game II (game theory)
[case sharing] let the development of education in the new era advance with "number"
leetcode-224:基本计算器
2022.2.14 resumption
File operation io-part2
Problèmes de configuration lex & yacc & Bison & Flex
tail -f 、tail -F、tailf的区别
FPGA - 7 Series FPGA internal structure clocking -04- multi area clock
【C语言】分支和循环语句(上)
[AUTOSAR eight OS]
链表内指定区间反转
About qbytearray storage hexadecimal and hexadecimal conversion
数组与集合性能比较
文件操作IO-Part2
【AutoSAR 二 AppL概述】
瑞萨RZ/G2L ARM开发板存储读写速度与网络实测
Leetcode-871: minimum refueling times
First hand evaluation of Reza electronics rz/g2l development board
图解网络:什么是虚拟路由器冗余协议 VRRP?
比较版本号