当前位置: 首页 > news >正文

LeetCode - 贪心算法 (Greedy Algorithm) 集合 [分配问题、区间问题]

欢迎关注我的CSDN:https://spike.blog.csdn.net/
本文地址:https://spike.blog.csdn.net/article/details/139242199

饼干

贪心算法,是在每一步选择中,都采取当前状态下,最好或最优(即最有利)的选择,从而希望导致结果是最好或最优的算法,在解决各种问题时被广泛应用,包括数组操作、字符串处理、图论等。

贪心算法包括:分配问题区间问题

  1. 455. 分发饼干 - 分配问题
  2. 135. 分发糖果 - 分配问题
  3. 605. 种花问题 - 分配问题
  4. 406. 根据身高重建队列 - 分配问题
  5. 435. 无重叠区间 - 区间问题
  6. 452. 用最少数量的箭引爆气球 - 区间问题
  7. 763. 划分字母区间 - 区间问题
  8. 121. 买卖股票的最佳时机 - 区间问题

1. 分配问题

455. 分发饼干 - 分配问题:

class Solution:def findContentChildren(self, g: List[int], s: List[int]) -> int:"""时间复杂度,来自于排序,O(mlogm + nlogn)空间复杂度,类似,O(logm + logn)"""g = sorted(g)  # 排序s = sorted(s)n, m = len(g), len(s)  # 序列数量i, j = 0, 0while i < n and j < m:  # 全部遍历if g[i] <= s[j]:  # 判断是否吃饱i += 1  # 孩子满足条件j += 1  # 饼干满足条件return i

135. 分发糖果 - 分配问题:

class Solution:def candy(self, ratings: List[int]) -> int:"""时间复杂度 O(n),空间复杂度 O(n)"""n = len(ratings)  # 序列长度res = [1] * n  # 每个孩子至少1个糖果# 正序遍历for i in range(1, n):if ratings[i] > ratings[i-1]:res[i] = res[i-1] + 1  # 要是后面+1# print(f"[Info] res: {res}")# 逆序遍历for i in range(n-1, 0, -1):if ratings[i-1] > ratings[i]:# 逆序需要最大值res[i-1] = max(res[i-1], res[i]+1)  # print(f"[Info] res: {res}")return sum(res)

605. 种花问题 - 分配问题:

class Solution:def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:"""时间复杂度 O(n),空间复杂度 O(1)"""res = 0  # 种花数量m = len(flowerbed)  # 花坛长度for i in range(m):# 前面是0,中间是0,最后是0,注意边界if (i==0 or flowerbed[i-1] == 0) and (flowerbed[i] == 0) and (i==m-1 or flowerbed[i+1]==0):res += 1flowerbed[i] = 1return res >= n

406. 根据身高重建队列 - 分配问题,读懂题,根据 -p[0] 和 p[1] 排序,再进行插入,根据 p[1],进行插入。

class Solution:def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:"""插入之前的位置时间O(n^2),空间O(logn)"""# p[0] 从大到小排序,再次根据 p[1] 从小到大排序people.sort(key=lambda x: (-x[0], x[1]))  # print(f"[Info] people: {people}")n = len(people)  # 人数res = []for p in people:# print(f"[Info] res: {res}")# 根据 p 值的第2位 [正好有k个人],进行排序插入res.insert(p[1], p)  # 在p[1]前一个位置插入return res

2. 区间问题

435. 无重叠区间 - 区间问题

class Solution:def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:"""时间复杂度 O(nlogn) 空间复杂度 O(logn)"""# 根据 end 值排序intervals = sorted(intervals, key=lambda x: x[1])# print(f"[Info] intervals: {intervals}")n = len(intervals)res = 0prev = intervals[0][1]  # 第1个值的末尾值for i in range(1, n):  # 从第2个值开始if intervals[i][0] < prev:  # 前值小于后值res += 1  # 相交else:prev = intervals[i][1]  # 遍历下一个return res

452. 用最少数量的箭引爆气球 - 区间问题,435 题的变换

class Solution:def findMinArrowShots(self, points: List[List[int]]) -> int:"""区间类型题,与 435 类似时间复杂度 O(nlogn),空间复杂度 O(logn)"""# 尾部排序points = sorted(points, key=lambda x: x[1])n = len(points)prev = points[0][1]  # 前值res = 0for i in range(1, n):if prev >= points[i][0]:res += 1  # 重叠值,即1箭射中2个else:prev = points[i][1]return n - res  # 最终值是差值

763. 划分字母区间 - 区间问题,记录字母最后出现的位置,与之前最大位置比较。

class Solution:def partitionLabels(self, s: str) -> List[int]:"""时间复杂度 O(n),空间复杂度 O(len(s))"""n=len(s)  # 序列长度last=[0]*26  # 字母数量# 遍历获取最后出现的位置for i in range(n):j=ord(s[i])-ord('a')last[j]=max(i,last[j])  # 字母最后出现的位置start,end=0,0res=[]for i in range(n):j=ord(s[i])-ord('a')# 当前字母j最后出现的位置last[j],与之前end,取最大值end=max(end,last[j])if end==i:  # end如果等于ires.append(end-start+1) # 序列长度start=end+1  # 起始位置移动return res

121. 买卖股票的最佳时机 - 区间问题

class Solution:def maxProfit(self, prices: List[int]) -> int:"""时间复杂度 O(n),空间复杂度 O(1)"""n=len(prices)  # 全部数量res=0  # 结果for i in range(1,n):# 累加区间价格res+=max(0,prices[i]-prices[i-1])return res
http://www.lryc.cn/news/355515.html

相关文章:

  • Linux中ftp配置
  • BWVS 靶场测试
  • c++ 里重解释转换之于引用 reinterpret_cast< long >
  • JAVASE2
  • ora-00392 ora-00312错误处理
  • 网页、h5默认滚动条样式重构
  • 香橙派AIpro测评上手指南
  • GBDT 算法【python,机器学习,算法】
  • 软考 系统架构设计师系列知识点之SOME/IP与DDS(3)
  • 将AI大模型装进你的手机,你愿意么?
  • 前端面试题12-22
  • 【论文解读】Performance of AV1 Real-Time Mode
  • java处理中文脱敏
  • 【Linux网络】端口及UDP协议
  • Unity 生成模版代码
  • 【ai】chatgpt的plugin已经废弃
  • 2024年03月 Python(四级)真题解析#中国电子学会#全国青少年软件编程等级考试
  • 多旋翼无人机机场考哪些内容?
  • 【前端每日基础】day23——箭头函数
  • 27.Java中单例模式的实现方式
  • C#面:当一个线程进入一个对象的方法后,其它线程是否可以进入该对象的方法?
  • express框架下后端获取req.body报错undefined
  • Element plus 低版本弹窗组件添加拖拽功能
  • 计算机组成原理易混淆知识点总结(持续更新)
  • 【STM32踩坑】HAL固件库版本过高导致烧录后无法运行问题
  • 芯片丝印反查
  • C语言之指针详解(5)(含有易错笔试题)
  • discuzX2.5的使用心得 札记一
  • 【Python】 探索Django框架的高并发处理能力
  • C-数据结构-平横二叉树