LeetCode解题报告 452. Minimum Number of Arrows to Burst Balloons [medium]

题目描述

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).     

解题思路

题目看起来很长,其实就是可以想象成一排气球飘在空中,上下位置可以随意飘动,左右位置固定,用一支箭可以穿破多个有重叠部分的浮动在不同上下空间上的气球,求最少需要多少支箭。将气球的位置看成数组,数组代表x轴上一定长度区域的位置,如果有交集就可以使用同一支箭。
使用贪心算法,开始时第一支箭一定要在第一个气球的范围内,为了覆盖尽可能多的别的气球,假设箭在最左边气球的最右边,依次向右遍历气球,当某个气球(标记为*)的起点比箭所在位置(第一个气球的最右边)大的时候,需要多加一支箭,并且更新箭的位置为新气球(标记为*的这个气球)的最右边。
算法的关键在于对气球的排序,以数组的end值(最右边)为基准,从小到大排序,而不是以start值(最左边)为基准。这是因为有可能出现第二个气球比第一个气球的start大而end更小,如[1,10]和[3,6],这样以来如果以左边为基准排序,那么第一个气球为[1,10],箭在x=10处,就需要多加一支本不需要的箭来刺穿[3,6];正确的排序之后第一支箭应该在x=6处,这样就能用一支刺破这两个气球了。

时间复杂度:

排序的复杂度为O(N*logN),贪心的复杂度为O(N),总复杂度为O(N*N*logN)。

代码如下:
class Solution {
public:
    static bool secondcompare(pair<int, int>&a, pair<int, int>&b){
        return a.second<b.second;
    }
    int findMinArrowShots(vector<pair<int, int>>& points) {
        if (points.size()==0) {
            return 0;
        }
        sort(points.begin(), points.end(), secondcompare);
        int sum=1;
        int bursting=points[0].second;
        for (int i=0; i<points.size(); i++) {
            if (points[i].first>bursting) {
                sum++;
                bursting=points[i].second;
            }
        }
        return sum;
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值