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

探讨了如何通过计算最少的垂直箭矢射击次数来击破所有水平分布的气球。采用贪心算法,首先对气球的结束坐标进行排序,接着通过遍历判断每个气球是否能被当前箭矢射中,若不能,则增加箭矢数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题

  • 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 <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
    int findMinArrowShots(vector<pair<int, 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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值