【LeetCode】452.用最少数量的箭引发气球

打印 上一主题 下一主题

主题 564|帖子 564|积分 1692

能够找到问题的解法与把问题足够简化是天壤之别。比如我知道这题可以用贪心算法来办理,但是代码实现的过程中就走上了复杂的路,但是官方题解给的代码则相称轻巧。这说明我思考的不够深入,导致化繁为简的能力不够强。
  1. 标题


2. 分析

一道贪心标题。
3. 代码

  1. class Solution:
  2.     def findMinArrowShots(self, points: List[List[int]]) -> int:
  3.         # 贪心算法        
  4.         points = sorted(points, key = lambda x:x[0])
  5.         print(points)
  6.         idx = 0
  7.         cnt = 0
  8.         prob = idx + 1
  9.         while(idx < len(points) and prob < len(points)):
  10.             left, right = points[idx]            
  11.             while(prob < len(points)):
  12.                 next_left, next_right = points[prob]
  13.                 # 如果下一个节点满足条件
  14.                 if left <= next_left <= right:
  15.                     # 更新
  16.                     left = max(left, next_left)
  17.                     right = min(right, next_right)
  18.                     prob += 1
  19.                 else:               
  20.                     # 更新 idx 的值
  21.                     idx = prob
  22.                     cnt+=1 # 计数结果
  23.                     prob += 1
  24.                     break
  25.         if idx < len(points):
  26.             cnt += 1
  27.         return cnt
复制代码
上面这版代码的看着很复杂。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

去皮卡多

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表