【力扣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的代码,好好好好起来了!
相关推荐
ComputerInBook4 分钟前
代数基本概念理解——特征向量和特征值
人工智能·算法·机器学习·线性变换·特征值·特征向量
中屹指纹浏览器14 分钟前
2025技术干货:国内静态 IP 搭配指纹浏览器的加密绑定与跨区域优化方案
经验分享·笔记
不能只会打代码14 分钟前
力扣--3433. 统计用户被提及情况
java·算法·leetcode·力扣
Ccjf酷儿32 分钟前
操作系统 李治军 4 设备驱动与文件系统
笔记
biter down1 小时前
C++ 解决海量数据 TopK 问题:小根堆高效解法
c++·算法
用户6600676685391 小时前
斐波那契数列:从递归到缓存优化的极致拆解
前端·javascript·算法
初夏睡觉1 小时前
P1055 [NOIP 2008 普及组] ISBN 号码
算法·p1055
程芯带你刷C语言简单算法题1 小时前
Day28~实现strlen、strcpy、strncpy、strcat、strncat
c语言·c++·算法·c
踏浪无痕1 小时前
周末拆解:QLExpress 如何做到不编译就能执行?
后端·算法·架构
一个不知名程序员www1 小时前
算法学习入门--- 树(C++)
c++·算法