去皮卡多 发表于 2024-8-14 20:20:12

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

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

https://i-blog.csdnimg.cn/direct/490c60dedc3642a3ae8fe70def62de4d.png
2. 分析

一道贪心标题。
3. 代码

class Solution:
    def findMinArrowShots(self, points: List]) -> int:
      # 贪心算法      
      points = sorted(points, key = lambda x:x)
      print(points)
      idx = 0
      cnt = 0
      prob = idx + 1
      while(idx < len(points) and prob < len(points)):
            left, right = points            
            while(prob < len(points)):
                next_left, next_right = points
                # 如果下一个节点满足条件
                if left <= next_left <= right:
                  # 更新
                  left = max(left, next_left)
                  right = min(right, next_right)
                  prob += 1
                else:               
                  # 更新 idx 的值
                  idx = prob
                  cnt+=1 # 计数结果
                  prob += 1
                  break
      if idx < len(points):
            cnt += 1
      return cnt
上面这版代码的看着很复杂。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 【LeetCode】452.用最少数量的箭引发气球