在二维空间中有许多球形的气球。对于每个气球,提供的输入是水平方向上,气球直径的开始和结束坐标。由于它是水平的,所以y坐标并不重要,因此只要知道开始和结束的x坐标就足够了。开始坐标总是小于结束坐标。平面内最多存在104个气球。
一支弓箭可以沿着x轴从不同点完全垂直地射出。在坐标x处射出一支箭,若有一个气球的直径的开始和结束坐标为 xstart,xend, 且满足 xstart ≤ x ≤ xend,则该气球会被引爆。可以射出的弓箭的数量没有限制。 弓箭一旦被射出之后,可以无限地前进。我们想找到使得所有气球全部被引爆,所需的弓箭的最小数量。 Example:
输入: [[10,16], [2,8], [1,6], [7,12]] 输出: 2 解释: 对于该样例,我们可以在x = 6(射爆[2,8],[1,6]两个气球)和 x = 11(射爆另外两个气球)。
首先根据每个气球的结束坐标将数组排序(考虑整型溢出), 再设置一个first_end标志,初始时置为第一个气球的结束 if(x_start>first_end),则箭的数量+1;
代码:
public static int findMinArrowsShot(int[][] points){ if(points.length==0){/*若数组为空则返回*/ return 0; } /*对points进行排序*/ Arrays.sort(points, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { if(o1[1]<o2[1]){/*考虑整型溢出案例:[[-2147483646,-2147483645],[2147483646,2147483647]]*/ return -1; }else{ return 1; } } }); int arrows = 1; /*初始化x_start,x_end,将first_end初始为第一个气球的结束坐标*/ int x_start,x_end,first_end = points[0][1]; for (int[] x:points) { x_start = x[0]; x_end = x[1]; if(first_end<x_start){ arrows++; first_end = x_end; } } return arrows; }测试:
public static void main(String[] args) { int[][] points = {{10,16},{2,8},{1,6},{7,12}}; System.out.println(findMinArrowsShot(points)); }输出:
2 Process finished with exit code 0