Greedy--Minimum Number of Arrows to Burst Balloons (Medium)

原题

  • Problem Description

    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.

  • Sample Input

    [[10,16], [2,8], [1,6], [7,12]]

  • Sample Output

    2

解题思路:

题目大概意思就是:
给定了每一个气球的区间(起始点和终止点),判断需要多少弓箭手才能射爆所有的气球(一支箭可以射穿多个气球)

贪心:

此题贪心在于->>对所有的气球的区间进行排序,然后每发射一个弓箭,便搜索所有能够被射中的气球,一个不落。

代码思路:

1、对所有气球的区间通过上界进行排序。
2、以第一个气球的区间为第一把弓箭的射击范围区间,之后逐个判断后面的气球的区间是否和弓箭的射击区间有交集,若有交集则弓箭也可射中此气球并更新弓箭的射击区间,直至有气球无法被此弓箭射中。
3、再一次增加一个弓箭,以上一个无法被射中的气球的区间为此弓箭的射击范围区间。

代码:

#include 
#include 
using namespace std;
class Solution {
public:
    int findMinArrowShots(vectorint, int>>& points) {
        if (points.size() == 0)
            return 0;
        sort(points.begin(), points.end(), cmp);//begin()和end()返回的是迭代器
        int shootNum = 1;//初始化弓箭手的数量为1
        int shootBegin = points[0].first;//初始化弓箭手的射击区域
        int shootEnd = points[0].second;
        for (int i = 1; i < points.size(); i++)
        {
            if (points[i].first <= shootEnd)//此气球在弓箭射击范围内
            {
                shootBegin = points[i].first;
                if (points[i].second <= shootEnd)
                {
                    shootEnd = points[i].second;
                }
            }else//无法射中此气球->增加一个弓箭,更新弓箭区间
            {
                shootNum++;
                shootBegin = points[i].first;
                shootEnd = points[i].second;
            }
        }
        return shootNum;
    }
    static bool  cmp(const pair<int,int>&a,const pair<int,int>&b)
    {
        return a.first < b.first;
    }
};

你可能感兴趣的:(LeetCode,贪心算法)