leetcode452. Minimum Number of Arrows to Burst Balloons

题目要求

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;
    }

你可能感兴趣的:(java,leetcode)