leetcode452. detonate the balloon with a minimal number of arrows

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:

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

Output:
2

Explanation:
For this sample, we can x = 6 (shot blast [2,8], [1,6] two balloons) and x = 11 (the other two balloons shot blasting).

Thinking: I do not want to write a little code annotated /

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[0] - o2[0];//开始端点升序
      }
    });
    int ans=1;
    int end=points[0][1];
    for(int i=1;i<points.length;i++){
        if(points[i][0]>end){
            //新的一戳
            end=points[i][1];
            ans++;
        }else{
            //和之前的一次戳破,更新最左结束端点
            end=Math.min(points[i][1],end);
        }
    }
    return ans;
  }
}

 

Published 537 original articles · won praise 10000 + · views 1.31 million +

Guess you like

Origin blog.csdn.net/hebtu666/article/details/104279955