第八章 贪心算法 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
相关推荐
汀、人工智能6 小时前
[特殊字符] 第40课:二叉树最大深度
数据结构·算法·数据库架构·图论·bfs·二叉树最大深度
沉鱼.446 小时前
第十二届题目
java·前端·算法
大熊背7 小时前
ISP Pipeline中Lv实现方式探究之三--lv计算定点实现
数据结构·算法·自动曝光·lv·isppipeline
西岸行者8 小时前
BF信号是如何多路合一的
算法
大熊背8 小时前
ISP Pipeline中Lv实现方式探究之一
算法·自动白平衡·自动曝光
罗西的思考8 小时前
【OpenClaw】通过 Nanobot 源码学习架构---(5)Context
人工智能·算法·机器学习
Liudef069 小时前
后量子密码学(PQC)深度解析:算法原理、标准进展与软件开发行业的影响
算法·密码学·量子计算
OYpBNTQXi10 小时前
SEAL全同态加密CKKS方案入门详解
算法·机器学习·同态加密
蚂蚁数据AntData11 小时前
破解AI“机器味“困境:HeartBench评测实践详解
大数据·人工智能·算法·机器学习·语言模型·开源
ZC跨境爬虫11 小时前
Python异步IO详解:原理、应用场景与实战指南(高并发爬虫首选)
爬虫·python·算法·自动化