Leetcode452. Arrow detonated with minimal balloon

Subject description:

There are many spherical balloons in two-dimensional space. For each balloon, the input is provided in the horizontal direction, the diameter of the balloon beginning and end coordinates. Because it is horizontal, y coordinates are not so important, so long as we know the beginning and end of the x-coordinate is sufficient. Start coordinates is always less than the end of the coordinates. The presence of up to 104 balloons plane.

A bow and arrow may be emitted from different points along the x axis perpendicular completely. Emitting an arrow at coordinates x, if the diameter of a start and end coordinates of the balloon xstart, xend, and satisfy xstart ≤ x ≤ xend, the balloon will be detonated. The number of bows can be emitted without limitation. Once the bow and arrow is shot, you can forward indefinitely. We all want to find that all the balloons were detonated, the minimum required number of bows and arrows.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/minimum-number-of-arrows-to-burst-balloons

Ideas: + greedy algorithm with sorting problem-solving. To sort list pointers to the left end in ascending order, and then define a list scope, the range to a new record may occur arrow. Order traversal list pointers, if the representative interval intersects the scope and range of the balloon, the update scope of intersection, the arrow so that within this range may also incorporate new Shepo the balloon, or the number of arrows + 1, scope updated to a new balloon It ranges.

Code (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

 

Guess you like

Origin www.cnblogs.com/szqfreiburger/p/11839479.html