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
相关推荐
不穿格子的程序员12 小时前
从零开始写算法——普通数组篇:缺失的第一个正数
算法·leetcode·哈希算法
Nebula_g12 小时前
线程进阶: 无人机自动防空平台开发教程(更新)
java·开发语言·数据结构·学习·算法·无人机
rit843249913 小时前
基于MATLAB的环境障碍模型构建与蚁群算法路径规划实现
开发语言·算法·matlab
hoiii18713 小时前
MATLAB SGM(半全局匹配)算法实现
前端·算法·matlab
独自破碎E13 小时前
大整数哈希
算法·哈希算法
纤纡.13 小时前
逻辑回归实战进阶:交叉验证与采样技术破解数据痛点(二)
算法·机器学习·逻辑回归
czhc114007566313 小时前
协议 25
java·开发语言·算法
范纹杉想快点毕业13 小时前
状态机设计与嵌入式系统开发完整指南从面向过程到面向对象,从理论到实践的全面解析
linux·服务器·数据库·c++·算法·mongodb·mfc
fish-man13 小时前
测试加粗效果
算法
晓131313 小时前
第二章 【C语言篇:入门】 C 语言基础入门
c语言·算法