第八章 贪心算法 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
相关推荐
加农炮手Jinx8 分钟前
LeetCode 72. Edit Distance 题解
算法·leetcode·力扣
借雨醉东风13 分钟前
程序分享--常见算法/编程面试题:旋转矩阵
c++·线性代数·算法·面试·职场和发展·矩阵
_深海凉_18 分钟前
LeetCode热题100-打家劫舍
算法·leetcode·职场和发展
jghhh011 小时前
使用 MATLAB 实现支持向量回归 (SVR) 预测未来数据
算法·matlab
云泽8081 小时前
笔试算法 - 双指针篇(二):四大经典求和题型 + 有效三角形计数问题
c++·算法
刀法如飞3 小时前
【合并已排序数组的三种实现策略,哪一种更可取?】
算法·程序员
王老师青少年编程3 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【区间贪心】:种树
c++·算法·贪心·csp·信奥赛·区间贪心·种树
hi_ro_a3 小时前
C++ 哈希表封装 unordered_map /unordered_set
数据结构·c++·算法·哈希算法
Jasmine_llq7 小时前
《B4447 [GESP202512 二级] 环保能量球》
数据结构·算法·数学公式计算(核心)·整数除法算法·多组数据循环处理·输入输出算法·简单模拟算法
蔡大锅7 小时前
🔥 在线学习算力平台推荐-Hyper.AI
人工智能·算法