Leetcode算法学习日志-452 Minimum Number of Arrows to Burst Balloons

来源:互联网 发布:阿里云开放华北区域 编辑:程序博客网 时间:2024/06/06 01:16

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

题意分析


有多个长形的气球,每个气球有一个 xstart和一个xend,不同气球可以重合(在y方向不重合),如果射箭的位置x满足 xstart ≤ x ≤ xend,则该气球被扎破,求最少用多少只箭能扎破所有气球。

解法分析


先分析怎么样的气球一定会消耗一支箭,由于相互不重合的气球一定需要不同的箭来射穿,所以找互不相交的气球数的最大值,这时可以猜想这个最大值就是需要箭数最小值,下面来证明这个猜想,已经得到一组最大不相交气球,而射穿其中一个气球不能将与之有交的气球都射穿,则说明与此气球有交的气球有相互独立的气球,则说明现有最大不相交气球数不是最大,与假设矛盾。为了找到最大不相交的气球数,类似活动选择问题,将xend从低到高排序,贪心选择xend最低的气球做为最大不相交气球组的第一个气球。C++代码如下:

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






阅读全文
0 0
原创粉丝点击