ToB企服应用市场:ToB评测及商务社交产业平台

标题: 【LeetCode】452.用最少数量的箭引发气球 [打印本页]

作者: 去皮卡多    时间: 2024-8-14 20:20
标题: 【LeetCode】452.用最少数量的箭引发气球
能够找到问题的解法与把问题足够简化是天壤之别。比如我知道这题可以用贪心算法来办理,但是代码实现的过程中就走上了复杂的路,但是官方题解给的代码则相称轻巧。这说明我思考的不够深入,导致化繁为简的能力不够强。
  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企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4