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<int[]>() {
            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;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容