1705. 吃苹果的最大数量
解法:优先队列
该题思路很简单,每天吃最早腐烂的水果即可,因此需要对每天已有苹果的腐烂日期进行判断,这时可以考虑使用优先队列,用最小堆实现,每次取出最早腐烂水果即可。
class Solution:
def eatenApples(self, apples: List[int], days: List[int]) -> int:
ans = 0
pq = []
i = 0
while i < len(apples):
# 弹出第i天已腐烂的水果
while pq and pq[0][0] <= i:
heappop(pq)
if apples[i]:
heappush(pq, [i + days[i], apples[i]])
if pq:
pq[0][1] -= 1
# 若该腐烂日期前的水果已被吃完则弹出
if pq[0][1] == 0:
[添加链接描述](https://leetcode-cn.com/problems/sort-array-by-parity/) heappop(pq)
ans += 1
i += 1
while pq:
while pq and pq[0][0] <= i:
heappop(pq)
if len(pq) == 0:
break
p = heappop(pq)
num = min(p[0] - i, p[1])
ans += num
i += num
return ans
905. 按奇偶排序数组
解法:双指针
采用类似快速排序的方法,维护左右两个指针i, j,根据以下情况移动/交换指针元素。
class Solution(object):
def sortArrayByParity(self, A):
i, j = 0, len(A) - 1
while i < j:
if A[i] % 2 > A[j] % 2:
A[i], A[j] = A[j], A[i]
if A[i] % 2 == 0: i += 1
if A[j] % 2 == 1: j -= 1
return A