第八章 贪心算法 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
相关推荐
海琴烟Sunshine29 分钟前
leetcode 383. 赎金信 python
python·算法·leetcode
cynicme7 小时前
力扣3228——将 1 移动到末尾的最大操作次数
算法·leetcode
熬了夜的程序员7 小时前
【LeetCode】109. 有序链表转换二叉搜索树
数据结构·算法·leetcode·链表·职场和发展·深度优先
随意起个昵称7 小时前
【递归】二进制字符串中的第K位
c++·算法
mjhcsp8 小时前
C++ 循环结构:控制程序重复执行的核心机制
开发语言·c++·算法
立志成为大牛的小牛8 小时前
数据结构——四十一、分块查找(索引顺序查找)(王道408)
数据结构·学习·程序人生·考研·算法
xier_ran8 小时前
深度学习:RMSprop 优化算法详解
人工智能·深度学习·算法
地平线开发者8 小时前
不同传感器前中后融合方案简介
算法·自动驾驶
地平线开发者8 小时前
征程 6X 常见 kernel panic 问题
算法·自动驾驶
com_4sapi9 小时前
2025 权威认证头部矩阵系统全景对比发布 双榜单交叉验证
大数据·c语言·人工智能·算法·矩阵·机器人