Leetcode452. 用最小的箭引爆气球

题目描述:

在二维空间中有许多球形的气球。对于每个气球,提供的输入是水平方向上,气球直径的开始和结束坐标。由于它是水平的,所以y坐标并不重要,因此只要知道开始和结束的x坐标就足够了。开始坐标总是小于结束坐标。平面内最多存在104个气球。

一支弓箭可以沿着x轴从不同点完全垂直地射出。在坐标x处射出一支箭,若有一个气球的直径的开始和结束坐标为 xstart,xend, 且满足  xstart ≤ x ≤ xend,则该气球会被引爆。可以射出的弓箭的数量没有限制。 弓箭一旦被射出之后,可以无限地前进。我们想找到使得所有气球全部被引爆,所需的弓箭的最小数量。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-number-of-arrows-to-burst-balloons

思路:用排序+贪婪算法解题。给list pointers排序,以左边端点从小到大的顺序,然后定义一个list scope,以记录新的箭头可能出现的范围。顺序遍历list pointers,如果代表气球范围的区间和scope相交,则更新scope为交集,这样在此范围内的箭头可以也把新的该气球射破,否则箭头数量+1,scope更新为新的气球的范围。

代码(python 3)

class Solution:
    def findMinArrowShots(self, points: List[List[int]]) -> int:
        if points==[]:
            return 0
        #sorting the list
        points.sort(key=lambda x:x[0])
        
        #scope: the current probable scope for a new bullet
        scope=[float("-inf"),float("+inf")]
        numbers=0
        for interval in points:
            if interval[0]>=scope[0] and interval[0]<=scope[1]:
                scope=[interval[0],min(interval[1],scope[1])]
            else:
                scope=interval
                numbers+=1
                
        numbers+=1
        return numbers
原文地址:https://www.cnblogs.com/szqfreiburger/p/11839479.html