当前位置:网站首页>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
边栏推荐
- MySQL multi table joint deletion
- [AUTOSAR twelve mode management]
- [flutter] icons component (load the built-in icon of flutter | display the material design icon completely)
- 1.11 - bus
- 【C语言】分支和循环语句(上)
- Leetcode-2280: represents the minimum number of line segments of a line graph
- 【AutoSAR 七 工具链简介】
- The arm core board / development board of Feiling equipped with Ti am62x made its debut in embedded world 2022
- [AUTOSAR nine c/s principle Architecture]
- Overlay of shutter (Pop-Up)
猜你喜欢
瑞萨RZ/G2L ARM开发板存储读写速度与网络实测
Data analysis, thinking, law breaking and professional knowledge -- analysis method (I)
1.11 - bus
Liad: the consumer end of micro LED products is first targeted at TVs above 100 inches. At this stage, it is still difficult to enter a smaller size
Linear programming of mathematical modeling (including Matlab code)
文件操作IO-Part2
Arduino开发之按键检测与正弦信号输出
[AUTOSAR VI description document]
【爱死机】《吉巴罗》被忽略的细节
Understanding and distinguishing of some noun concepts in adjustment / filtering
随机推荐
1.12 - 指令
In the first half of 2022, there are 10 worth seeing, and each sentence can bring you strength!
[AUTOSAR I overview]
What is needed to develop a domestic arm intelligent edge computing gateway
[introduction to AUTOSAR seven tool chain]
leetcode-2115:从给定原材料中找到所有可以做出的菜
Understanding and distinguishing of some noun concepts in adjustment / filtering
Usage of using clause in kingbases alter table
拥抱平台化交付的安全理念
【AutoSAR 九 C/S原理架构】
[C language] branch and loop statements (Part 1)
Key detection and sinusoidal signal output developed by Arduino
瑞萨RZ/G2L ARM开发板存储读写速度与网络实测
First hand evaluation of Reza electronics rz/g2l development board
[overview of AUTOSAR three RTE]
指针进阶(一)
【AutoSAR 八 OS】
数组与集合性能比较
Leetcode-1964: find the longest effective obstacle race route to each position
[AUTOSAR nine c/s principle Architecture]