LeetCode #452 - Minimum Number of Arrows to Burst Balloons

题目描述:

There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it's horizontal, y-coordinates don't matter and hence the x-coordinates of start and end of the diameter suffice. Start is always smaller than end. There will be at most 104 balloons.

An arrow can be shot up exactly vertically from different points along the x-axis. A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend. There is no limit to the number of arrows that can be shot. An arrow once shot keeps travelling up infinitely. The problem is to find the minimum number of arrows that must be shot to burst all balloons.

Example:

Input:[[10,16], [2,8], [1,6], [7,12]]
Output:2
Explanation:
One way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) and another arrow at x = 11 (bursting the other two balloons).

给定一组气球的横坐标范围,每次可以从任意的横坐标射箭,进而戳破在这个横坐标上的所有气球,求问最少需要多少箭才能把所有的气球戳破。首先我们需要对所有气球按照起点排序,那么对于第一个气球,我们自然选择在它的终点射出一箭,用一个变量存储这一箭的位置,那么如果第二个气球的起点小于或等于这个位置,我们就更新射箭的位置,让它等于第一个气球和第二个气球终点的最小值,这样就能把第一个气球和第二个气球都戳破;如果第二个气球的起点大于这个位置,那么就需要再射一箭,同时更新箭的位置,依次递推。

class Solution {
public:
    int findMinArrowShots(vector<pair<int, int>>& points) {
        if(points.size()==0) return 0;
        sort(points.begin(),points.end());
        int cur_end=points[0].second;
        int count=1;
        for(int i=1;i<points.size();i++)
        {
            if(points[i].first>cur_end) 
            {
                count++;
                cur_end=points[i].second;
            }
            else cur_end=min(cur_end,points[i].second);
        }
        return count;
    }
};

猜你喜欢

转载自blog.csdn.net/LawFile/article/details/81254614