代码随想录算法训练营day31 | 贪心算法理论基础,455.分发饼干 ,376. 摆动序列 ,53. 最大子序和

455.分发饼干

  • 第一反应是排序并利用最大值(也就是排好序的数组的最后一个元素)做比较。

  • 对比题解而言,不那么直观且需要考虑多种情况(通过debug完善),但运行时间要明显低于题解。

class Solution(object):
    def findContentChildren(self, g, s):
        """
        :type g: List[int]
        :type s: List[int]
        :rtype: int
        """
        g.sort()
        s.sort()
        ans = 0
        
        if len(g) == 0 or len(s) == 0:
            return 0
        
        times = len(g)
        while times > 0:
            if len(s) == 0:
                break
            if g[-1] <= s[-1]:
                ans += 1
                s.pop()
            g.pop()
            times -= 1
        return ans
  • 题解如下:

class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        g.sort()
        s.sort()
        ans = 0
        
        index = len(s)-1
        for i in range(len(g)-1, -1, -1):
            if index >= 0 and g[i] <= s[index]:
                ans += 1
                index -= 1
                
        return ans

376. 摆动序列(medium)

  • 思路trick

    • 删除单调坡度上的节点(不包括单调坡度两端的节点)

    • 实际操作上,其实连删除的操作都不用做,因为题目要求的是最长摆动子序列的长度,所以只需要统计数组的峰值数量就可以了(相当于是删除单一坡度上的节点,然后统计长度)

  • 代码trick

    • 统计峰值的时候,数组最左面和最右面是最不好统计的。如何实现?

    • e.g,[2,5],可以假设为[2,2,5],这样它就有坡度了即preDiff = 0。同时默认最右面有一个峰值,此时result就需要初始化为1。

class Solution:
    def wiggleMaxLength(self, nums: List[int]) -> int:
        preDiff = 0
        curDiff = 0
        res = 1  #默认最后端有一峰值
        
        for i in range(len(nums)-1):
            curDiff = nums[i+1] - nums[i]
            if preDiff * curDiff <= 0 and curDiff !=0:
                res += 1
                preDiff = curDiff
                
        return res

53. 最大子序和

  • 第一反应是滑动窗口,定义curSum, 以及双指针left and right. 

  • 滑动方式:right每移动一位,则更新curSum,如果curSum没有变化(与上一轮保持一致,说明当前sum较小,那么就left=right+1,right=left).

  • 贪心题解:

result = -float('inf')
        count = 0
        for i in range(len(nums)):
            count += nums[i]
            if count > result:
                result = count
            if count <= 0:
                count = 0
        return result

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值