【力扣hot100】刷题笔记Day23

前言

  • 这周是真要开组会了,要抓紧干点活了,先看能不能把今天的题先刷了

121. 买卖股票的最佳时机 - 力扣(LeetCode)

贪心

复制代码
```python
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        minPrice = float('inf')
        res = 0
        for price in prices:
            minPrice = min(minPrice, price)   # 记录波谷
            res = max(res, price - minPrice)  # 当前值减去波谷
        return res
```

55. 跳跃游戏 - 力扣(LeetCode)

贪心

复制代码
```python
class Solution:
    def canJump(self, nums: List[int]) -> bool:
        if len(nums) == 1: return True   # 只有1个直接到达
        maxDistance = 0
        for i in range(len(nums)-1):
            maxDistance = max(maxDistance, i + nums[i])  # 更新最远距离
            if i >= maxDistance:   # 如果当前到不了最远
                return False
        return True  # 遍历完说明可以到达最后
```

45. 跳跃游戏 II - 力扣(LeetCode)

贪心

复制代码
```python
class Solution:
    def jump(self, nums: List[int]) -> int:
        if len(nums) == 1: return 0   # 长度为1不用跳
        maxDistance = 0
        curDistance = 0
        res = 0
        for i in range(len(nums)):
           maxDistance = max(nums[i] + i, maxDistance)
           if i == curDistance:  # 到当前覆盖最远了,不得不跳一步
               res += 1   # 跳一步
               curDistance = maxDistance  # 更新当前能跳到的最远
               if curDistance >= len(nums) - 1:
                   break  # 如果能到达最后则退出
        return res
```

763. 划分字母区间 - 力扣(LeetCode)

贪心

复制代码
```python
class Solution:
    def partitionLabels(self, s: str) -> List[int]:
        mp = {}  # 映射,每个字母能达到的最远距离
        for i, c in enumerate(s):
            mp[c] = max(mp.get(c,0), i)
        maxDistance = lastEnd = 0
        res = []
        for i, c in enumerate(s):
            maxDistance = max(maxDistance, mp[c])  # 更新最远距离
            if maxDistance == i:    # 到达最远距离,进行切割
                res.append(maxDistance - lastEnd + 1)  # 将当前长度存入结果
                lastEnd = maxDistance + 1  # 更新起始坐标
        return res 
            
```

后言

  • 这几道题一个上午解决咯,而且能自己写出AC的代码,好好好好起来了!
相关推荐
仰泳的熊猫5 分钟前
LeetCode:51. N 皇后
数据结构·c++·算法·leetcode
独自破碎E6 分钟前
LeetCode 381: O(1) 时间插入、删除和获取随机元素 - 允许重复
java·算法·leetcode
鲸鱼在dn15 分钟前
大语言模型的后训练与“灾难性遗忘”问题——李宏毅2025大模型第六讲笔记
人工智能·笔记·语言模型
Miraitowa_cheems31 分钟前
LeetCode算法日记 - Day 81: 最大子数组和
java·数据结构·算法·leetcode·决策树·职场和发展·深度优先
徐子童43 分钟前
数据结构---优先级队列(堆)
java·数据结构·面试题·优先级队列··topk问题
学编程就要猛1 小时前
数据结构初阶:Java泛型
数据结构·1024程序员节
冯诺依曼的锦鲤1 小时前
算法练习:前缀和专题
开发语言·c++·算法
闭着眼睛学算法1 小时前
【双机位A卷】华为OD笔试之【哈希表】双机位A-跳房子I【Py/Java/C++/C/JS/Go六种语言】【欧弟算法】全网注释最详细分类最全的华子OD真题题解
java·c语言·c++·python·算法·华为od·散列表
Cathy Bryant2 小时前
线性代数直觉(二):二次型与“正定”
笔记·神经网络·考研·机器学习·数学建模
自信150413057592 小时前
初学者小白复盘15之指针(4)
c语言·数据结构·算法