LEETCODE-DAY31


title: LEETCODE-DAY31

date: 2024-03-22 19:50:30
tags:

今日内容:贪心算法455.分发饼干、376. 摆动序列、53. 最大子序和

T1

python 复制代码
class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        g.sort()
        s.sort()
        count=0
        i=len(g)-1
        j=len(s)-1
        while j>=0:
            while i>=0:
                if s[j]>=g[i]:
                    count+=1
                    break
                i-=1
            j-=1
        return count

g =

1,2

s =

1,2,3

输出

3

预期结果

2

break后的i-=1没执行

python 复制代码
class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        g.sort()
        s.sort()
        count=0
        i=len(g)-1
        j=len(s)-1
        while j>=0:
            while i>=0:
                if s[j]>=g[i]:
                    count+=1
                    i-=1
                    break
                i-=1
            j-=1
        return count

AC

python 复制代码

T2

python 复制代码
class Solution:
    def wiggleMaxLength(self, nums: List[int]) -> int:
        if len(nums) <= 1:
            return len(nums)  # 如果数组长度为0或1,则返回数组长度
        preDiff,curDiff ,result  = 0,0,1  #题目里nums长度大于等于1,当长度为1时,其实到不了for循环里去,所以不用考虑nums长度
        for i in range(len(nums) - 1):
            curDiff = nums[i + 1] - nums[i]
            if curDiff * preDiff <= 0 and curDiff !=0:  #差值为0时,不算摆动
                result += 1
                preDiff = curDiff  #如果当前差值和上一个差值为一正一负时,才需要用当前差值替代上一个差值
        return result

T3

python 复制代码
class Solution:
    def maxSubArray(self, nums):
        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
相关推荐
爪哇部落算法小助手42 分钟前
每日两题day23
算法
妮妮喔妮1 小时前
10.25复习LRU缓存[特殊字符]
算法
linff9111 小时前
hot 100 技巧题
数据结构·算法·leetcode
暴风鱼划水1 小时前
卡码网语言基础课(Python) | 19.洗盘子
python·算法
会编程是什么感觉...1 小时前
算法 - PEC校验
单片机·算法
再卷也是菜2 小时前
算法基础篇(8)贪心算法
算法·贪心算法·1024程序员节
AI科技星3 小时前
接近光速运动下的光速不变性:基于张祥前统一场论的推导与验证
数据结构·人工智能·经验分享·算法·计算机视觉
陈苏同学3 小时前
笔记1.4:机器人学的语言——三维空间位姿描述 (旋转矩阵 - 齐次变换矩阵 - 欧拉角 - 四元数高效表示旋转)
笔记·线性代数·算法·机器人
scx201310044 小时前
20251025 分治总结
数据结构·c++·算法
碧海银沙音频科技研究院4 小时前
DiVE长尾识别的虚拟实例蒸馏方法
arm开发·人工智能·深度学习·算法·音视频