452. detonated a balloon with a minimal number of arrows

452. detonated a balloon with a minimal number of arrows

Title Description

There are many spherical balloons in two-dimensional space. For each balloon, the input is provided in the horizontal direction, the diameter of the balloon beginning and end coordinates. Because it is horizontal, y coordinates are not so important, so long as we know the beginning and end of the x-coordinate is sufficient. Start coordinates is always less than the end of the coordinates. The presence of up to 104 balloons plane.

A bow and arrow may be emitted from different points along the x axis perpendicular completely. Emitting an arrow at coordinates x, if the diameter of a start and end coordinates of the balloon xstart, xend, and satisfy xstart ≤ x ≤ xend, the balloon will be detonated. The number of bows can be emitted without limitation. Once the bow and arrow is shot, you can forward indefinitely. We all want to find that all the balloons were detonated, the minimum required number of bows and arrows.

Example:

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

输出:
2

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

Code posted

class Solution {
    public int findMinArrowShots(int[][] points) {
        if (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 cnt = 1, end = points[0][1];
        for (int i = 1; i < points.length; i ++){
            if (points[i][0] > end){
                cnt ++;
                end = points[i][1];
            }
        }
        return cnt;
    }
}

Guess you like

Origin www.cnblogs.com/Tu9oh0st/p/10994186.html