【LeetCode】452. Detonate the balloon with the minimum number of arrows

There are many spherical balloons in two-dimensional space. For each balloon, the input provided is the start and end coordinates of the balloon's diameter in the horizontal direction. Since it's horizontal, the ordinate doesn't matter, so it's enough to know the start and end abscissas. The start coordinate is always less than the end coordinate.

A bow and arrow can be shot perfectly perpendicular from different points along the x-axis. Shoot an arrow at coordinate x. If there is a balloon whose diameter starts and ends at coordinates xstart, xend, and satisfies xstart ≤ x ≤ xend, the balloon will be detonated. There is no limit to the number of bows that can be fired. Once the bow and arrow is fired, it can move forward indefinitely. We want to find the minimum number of bows needed to make all balloons explode.

Given an array of points, where points[i] = [xstart,xend], returns the minimum number of arrows that must be fired to detonate all balloons.

Example 1:

Input: points = [[10,16],[2,8],[1,6],[7,12]]
Output: 2
Explanation: For this example, x = 6 can shoot [2,8] ,[1,6] two balloons, and x = 11 pops the other two balloons

Ideas:

First, sort the array according to xend. Because you want to shoot arrows as little as possible, shoot arrows at the rightmost end of the shortest overlapping line segment (the horizontal coverage is the largest). Sorting according to xend can ensure that no line segment is missed.

image-20220118034138140

Code:

class Solution {
public:
    int findMinArrowShots(vector<vector<int>>& points) {
        sort(points.begin(),points.end(),[](vector<int>& lhs, vector<int>& rhs){
            return lhs[1]<rhs[1];
        });
        int res=1,pos=points[0][1];
        for(int i=1;i<points.size();i++){
            if(points[i][0]>pos){
                res++;
                pos=points[i][1];
            }
        }
        return res;
    }
};

Guess you like

Origin blog.csdn.net/pigpigpig64/article/details/122552184