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
相关推荐
写个博客26 分钟前
暑假算法日记第一天
算法
绿皮的猪猪侠28 分钟前
算法笔记上机训练实战指南刷题
笔记·算法·pta·上机·浙大
hie988941 小时前
MATLAB锂离子电池伪二维(P2D)模型实现
人工智能·算法·matlab
杰克尼1 小时前
BM5 合并k个已排序的链表
数据结构·算法·链表
.30-06Springfield2 小时前
决策树(Decision tree)算法详解(ID3、C4.5、CART)
人工智能·python·算法·决策树·机器学习
我不是哆啦A梦2 小时前
破解风电运维“百模大战”困局,机械版ChatGPT诞生?
运维·人工智能·python·算法·chatgpt
xiaolang_8616_wjl2 小时前
c++文字游戏_闯关打怪
开发语言·数据结构·c++·算法·c++20
small_wh1te_coder2 小时前
硬件嵌入式学习路线大总结(一):C语言与linux。内功心法——从入门到精通,彻底打通你的任督二脉!
linux·c语言·汇编·嵌入式硬件·算法·c
挺菜的3 小时前
【算法刷题记录(简单题)002】字符串字符匹配(java代码实现)
java·开发语言·算法
凌肖战6 小时前
力扣网编程55题:跳跃游戏之逆向思维
算法·leetcode