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

解题思路

这道题的解决思路其实就是找重叠区间最多的位置x的数量。此题采用贪心算法求解。算法共三步:

1、将存储气球位置的points数组按照每个气球的起始点的位置进行排序,便于后续操作。这里使用系统内置的sort函数。

2、设定初始可以放置箭矢发射的位置空间为0号气球的位置(排序后的points数组的0号元素points[0]),放置箭矢发射的位置空间的右边界用变量 end 记录。

3、假如第x个气球的左边界小于当前记录的 end 值,说明当前放置的箭矢可以射爆第x个气球,箭矢的数量不需要增加。但要注意,第x个气球的右边界可能小于当前记录的 end 值,此时需要将当前的重叠区域的右边界更新为第x个气球的右边界。否则,假如第x个气球的左边界已经大于当前记录的 end 值,那说明这个气球不能被射爆,要使用新的箭矢。箭矢的数量要加1,同时将 end 值更新为第x个气球的右边界。重复上述步骤直到遍历完所有气球。

注:由于points数组已经按照每个气球的左边界进行了排序,因此后面的算法过程不再需要记录气球的左边界的位置,因为从位置 end 射出的箭矢一定能射爆重叠区域的所有气球。

C++代码

class Solution {
public:
    int findMinArrowShots(vector<pair<int, int>>& points) {
        if(points.empty()) return 0;
        
        sort(points.begin(), points.end(), [](const pair<int, int> a, const pair<int, int> b){ return a.first < b.first; });
        
        int arrows = 1;
        int end = points[0].second;
        
        for(int i = 1; i < points.size(); i++) {
            if(points[i].first <= end) {
                if(end >= points[i].second)
                    end = points[i].second;
            }
            else {
                arrows++;
                end = points[i].second;
            }
        }
        return arrows;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZTao-z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值