【LeetCode】1705 and 905

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值