第八章 贪心算法 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
相关推荐
MicroTech20253 分钟前
微算法科技(NASDAQ:MLGO)基于后量子阈值算法的区块链隐私保护技术
科技·算法·区块链
qq_417129259 分钟前
基于C++的区块链实现
开发语言·c++·算法
2401_8324027512 分钟前
C++中的命令模式实战
开发语言·c++·算法
有一个好名字13 分钟前
力扣-钥匙和房间
算法·leetcode·深度优先
ZPC821014 分钟前
ROS2 独占内核
人工智能·python·算法·机器人
老鼠只爱大米19 分钟前
LeetCode经典算法面试题 #104:二叉树的最大深度(深度优先搜索、广度优先搜索等多种实现方案详细解析)
算法·leetcode·二叉树·dfs·bfs·深度优先搜索·广度优先搜索
疯狂的喵20 分钟前
分布式系统监控工具
开发语言·c++·算法
爱尔兰极光22 分钟前
LeetCode热题100--两数之和
算法·leetcode·职场和发展
2301_8223827625 分钟前
模板编译期排序算法
开发语言·c++·算法
m0_5613596730 分钟前
嵌入式C++调试技术
开发语言·c++·算法