第八章 贪心算法 part04

860. 柠檬水找零

这道题使用了构建了字典去查询的

python 复制代码
class Solution:
    def lemonadeChange(self, bills: List[int]) -> bool:
        yours = {"5":0,"10":0,"20":0}
        for i in range(len(bills)):
            if bills[i] == 5:
                yours["5"] += 1
            elif bills[i] == 10:
                if yours["5"] != 0:
                    yours["5"] -= 1
                    yours["10"] += 1
                else:
                    return False
            else:
                if yours["5"] != 0 and yours["10"] != 0:
                    yours["20"] += 1
                    yours["5"] -= 1
                    yours["10"] -= 1
                elif yours["5"] >= 3:
                    yours["5"] -= 3
                    yours["20"] += 1
                else:
                    return False
        print(yours)
        return True

406. 根据身高重建队列

python 复制代码
class Solution:
    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
        people.sort(key=lambda x: (-x[0], x[1]))
        que = []
        for p in people:
            que.insert(p[1], p)
        return que
        

感觉这道题十分简单,但是有想不到,贪心有时就是这样

452. 用最少数量的箭引爆气球

可能是因为贪心不能有一个固定的公式,所以总觉得做的很吃力,完全没有头绪,没有一个可以套的公式。

python 复制代码
class Solution:
    def findMinArrowShots(self, points: List[List[int]]) -> int:
        points.sort(key = lambda x:(x[0],x[1]))
        i = 1
        result = 1
        for i in range(1, len(points)):
            if points[i][0] > points[i - 1][1]:
                result += 1     
            else:
                points[i][1] = min(points[i - 1][1], points[i][1]) # 更新重叠气球最小右边界
        return result
相关推荐
二年级程序员5 分钟前
单链表算法题思路详解(上)
c语言·数据结构·c++·算法
wshzd15 分钟前
LLM之Agent(四十四)|使用 GRPO 算法训练多智能体系统用于复杂任务规划
算法
谁不学习揍谁!30 分钟前
基于python机器学习算法的农作物产量可视化分析预测系统(完整系统源码+数据库+详细文档+论文+详细部署教程+答辩PPT)获取方式
python·算法·机器学习
ADDDDDD_Trouvaille1 小时前
2026.2.13——OJ75-77题
c++·算法
重生之后端学习2 小时前
230. 二叉搜索树中第 K 小的元素
java·数据结构·算法·深度优先
近津薪荼2 小时前
dfs专题7—— 全排列
c++·学习·算法·深度优先
你的冰西瓜2 小时前
C++ STL算法——非修改序列算法
开发语言·c++·算法·stl
闻缺陷则喜何志丹2 小时前
P12275 [蓝桥杯 2024 国 Python B] 工厂|普及+
c++·算法·蓝桥杯·洛谷
宝贝儿好2 小时前
【强化学习】第九章:基于Action-Critic框架的强化学习
人工智能·python·深度学习·算法·动态规划
laplace01232 小时前
KL 散度1
人工智能·算法·agent·qwen