前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode452. Minimum Number of Arrows to Burst Balloons

leetcode452. Minimum Number of Arrows to Burst Balloons

作者头像
眯眯眼的猫头鹰
发布2019-11-12 16:26:42
4140
发布2019-11-12 16:26:42
举报

题目要求

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 104balloons.

An arrow can be shot up exactly vertically from different points along the x-axis. A balloon with xstartand xendbursts 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轴上的起始坐标和结束坐标。现在会以储值X轴的方向开枪,问最少开多少枪可以将所有的气球打落。

思路和代码

假设现在有一个气球位于xi-xj,假如在xj之前一枪不开,则该气球一定无法被击落。因此如果将所有气球的xj位置按照从小到大排序,并且从第一个气球的xj处开一枪,则可以知道该位置最多可以击落多少个气球。再从下一个气球的xj位置处开第二枪,依次递推。直到击落最后一个气球为止。

    public int findMinArrowShots(int[][] points) {
        if (points == null || points.length==0) {return 0;}
        Arrays.sort(points, Comparator.comparingInt(o -> o[1]));
        int count = 0;
        int index = 0;
        while (index < points.length) {
            int right = points[index][1];
            while (++index < points.length && points[index][0] <= right);
            count++;
        }
        return count;
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目要求
  • 思路和代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档