452. 用最少数量的箭引爆气球

用最少数量的箭引爆气球

在二维空间中有许多球形的气球。对于每个气球,提供的输入是水平方向上,气球直径的开始和结束坐标。由于它是水平的,所以y坐标并不重要,因此只要知道开始和结束的x坐标就足够了。开始坐标总是小于结束坐标。平面内最多存在104个气球。

一支弓箭可以沿着x轴从不同点完全垂直地射出。在坐标x处射出一支箭,若有一个气球的直径的开始和结束坐标为 xstart,xend, 且满足 xstart ≤ x ≤ xend,则该气球会被引爆。可以射出的弓箭的数量没有限制。 弓箭一旦被射出之后,可以无限地前进。我们想找到使得所有气球全部被引爆,所需的弓箭的最小数量。

Example:

输入:
[[10,16], [2,8], [1,6], [7,12]]

输出:
2

解释:
对于该样例,我们可以在x = 6(射爆[2,8],[1,6]两个气球)和 x = 11(射爆另外两个气球)。

思路+代码+注释:

class Interval {
        int start;
        int end;
        Interval() { start = 0; end = 0; }
        Interval(int s, int e) { start = s; end = e; }
    }

    public int findMinArrowShots(int[][] points) {
        /*
        思路:last记录上一个区间
        按照start从小到大对区间进行排序,如果前一个区间的end>=后一个区间的start那么区间可以合并,合并时取较大start、较小end;否则不能合并,
        此时可以用一个弓箭射穿已经合并的区间count++,然后将当前cur的start、end赋给last,继续比较,直到比较完所有区间,最后count++射穿最后一个合并的区间
         */
        if (points.length==0)
        {
            return 0;
        }
        int count=0;
        PriorityQueue<Interval> priorityQueue=new PriorityQueue<>(new Comparator<Interval>() {
            @Override
            public int compare(Interval o1, Interval o2) {
                return o1.start-o2.start;
            }
        });
        for (int[] ints:points
             ) {
            Interval interval=new Interval();
            interval.start=ints[0];
            interval.end=ints[1];
            priorityQueue.add(interval);
        }
        Interval first=priorityQueue.poll();
        int lastS=first.start;
        int lastE=first.end;
        while (priorityQueue.size()>0)
        {
            Interval cur=priorityQueue.poll();
            if (lastE>=cur.start)
            {
                if (cur.start>lastS)
                {
                    lastS=cur.start;
                }
                if (cur.end<lastE)
                {
                    lastE=cur.end;
                }
            }else {
                count++;
                lastS=cur.start;
                lastE=cur.end;
            }
        }
        count++;
        return count;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值