【力扣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的代码,好好好好起来了!
相关推荐
原野-2 分钟前
MySQL8新特性
数据结构·排序算法
月明长歌2 分钟前
【码道初阶】LeetCode面试题 17.14 最小 K 个数:两种堆解法的“同题不同命”
算法·leetcode·职场和发展
直有两条腿3 分钟前
【Redis】原理-数据结构
数据结构·数据库·redis
程芯带你刷C语言简单算法题4 分钟前
Day33~实现一个算法来识别一个字符串。
c语言·算法·c
学编程就要猛5 分钟前
算法:2.复写零
java·数据结构·算法
TL滕5 分钟前
从0开始学算法——第二十一天(链表练习)
笔记·学习·算法
LYFlied7 分钟前
【每日算法】LeetCode238. 除自身以外数组的乘积
数据结构·算法·leetcode·面试·职场和发展
仰泳的熊猫7 分钟前
1154 Vertex Coloring
数据结构·c++·算法·pat考试
_OP_CHEN7 分钟前
【算法基础篇】(三十七)图论基础之单源最短路:从原理到实战,4 大算法彻底吃透!
算法·图论
a程序小傲9 分钟前
京东Java面试被问:垃圾收集算法(标记-清除、复制、标记-整理)的比较
java·算法·面试