- 概述
优先队列是可以根据元素优先级顺序出队的队列。优先队列的底层数据结构可以是堆。
- Python中堆的使用
导入:import heapq
函数 | 功能 |
---|---|
heappush(heap, x) | 将x压入堆heap中,heap为列表 |
heappop(heap, x) | 弹出最小的元素(优先级最高) |
heapify(heap) | 让列表具有堆的性质 |
heapreplace(heap, x) | 弹出最小的元素并压入x |
nlargest(n, iter) | 返回iter中n个最大元素 |
nsmallest(n, iter) | 返回iter中n个最小元素 |
- 例题:
有一棵特殊的苹果树,一连 n 天,每天都可以长出若干个苹果。在第 i 天,树上会长出 apples[i] 个苹果,这些苹果将会在 days[i] 天后(也就是说,第 i + days[i] 天时)腐烂,变得无法食用。也可能有那么几天,树上不会长出新的苹果,此时用 apples[i] == 0 且 days[i] == 0 表示。
你打算每天 最多 吃一个苹果来保证营养均衡。注意,你可以在这 n 天之后继续吃苹果。
给你两个长度为 n 的整数数组 days 和 apples ,返回你可以吃掉的苹果的最大数目。
题目来源:LeetCode1705题
题目链接:https://leetcode-cn.com/problems/maximum-number-of-eaten-apples
分析:
优先吃掉最先腐烂的苹果,一定能保证吃掉的苹果数目最多。
参考解答:
class Solution:
def eatenApples(self, apples: List[int], days: List[int]) -> int:
h = []
i = ans = 0
while h or i < len(days):
if i < len(days) and apples[i] > 0:
heapq.heappush(h, (i + days[i], apples[i]))
while h and h[0][0] <= i:
heapq.heappop(h)
if h:
day, cnt = heapq.heappop(h)
ans += 1
if cnt > 1:
heapq.heappush(h, (day, cnt - 1))
i += 1
return ans