贪心策略---投飞镖刺破气球

投飞镖刺破气球

452. Minimum Number of Arrows to Burst Balloons (Medium)

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

Output:
2

题目描述:

  有若干个气球,给出了它们的直径两个端点的坐标(x轴),我们的工作是用一只箭来戳破气球。例如两个气球的直径分别是(1,6)和(2,8),那么我们就可以在x=6的坐标处发射一支箭从而将它们一起戳破。

思路分析:

  计算不重叠的区间个数,就是需要的飞镖数,[1,2]和[2,3]算是重叠区域。

代码:

class Solution {
    public int findMinArrowShots(int[][] points) {
        if(points==null||points.length==0)
            return 0;
        Arrays.sort(points,new Comparator<int[]>(){ //按坐标的尾元素进行排序,能保证最多的不重叠区间
            @Override
            public int compare(int[]o1,int[]o2){
                return o1[1]-o2[1];
            }
        });
        int res=1;
        int end=points[0][1];
        for(int i=1;i<points.length;i++){
            if(points[i][0]<=end)
                continue;
                res++;
                end=points[i][1];
            
        }
        return res;
    }
}
posted @ 2019-06-28 21:52  yjxyy  阅读(491)  评论(0编辑  收藏  举报