Minimum Number of Arrows to Burst Ballons

题目
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.

答案

class Solution {
    public int findMinArrowShots(int[][] points) {
        if(points.length == 0) return 0;
        // Sort the points from left to right, with its x-start
        // Let ans = 0, Iterate the sorted points from left to right, for each intersected groups of ballons, ans++
        Arrays.sort(points, new Comparator() {
            public int compare(int[] o1, int[] o2) {
                return(Integer.valueOf(o1[0]).compareTo(o2[0]));
            }
        });
        int ans = 0;
        int []intersections = new int[]{points[0][0], points[0][1]};
        for(int i = 1; i < points.length; i++) {
            // Not interseced with last group of points
            if(points[i][0] > intersections[1]) {
                ans++;
                intersections[0] = points[i][0];
                intersections[1] = points[i][1];
            }
            // Update intersections
            else {
                intersections[1] = Math.min(intersections[1], points[i][1]);
            }
        }
        // Account for the last group of points
        return ans + 1;
    }
}

你可能感兴趣的:(Minimum Number of Arrows to Burst Ballons)