LeetCode452-用最少数量的箭引爆气球

题目链接

英文链接:https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/

中文链接:https://leetcode-cn.com/problems/minimum-number-of-arrows-to-burst-balloons/

题目详述

在二维空间中有许多球形的气球。对于每个气球,提供的输入是水平方向上,气球直径的开始和结束坐标。由于它是水平的,所以y坐标并不重要,因此只要知道开始和结束的x坐标就足够了。开始坐标总是小于结束坐标。平面内最多存在104个气球。

一支弓箭可以沿着x轴从不同点完全垂直地射出。在坐标x处射出一支箭,若有一个气球的直径的开始和结束坐标为 xstart,xend, 且满足 xstart ≤ x ≤ xend,则该气球会被引爆。可以射出的弓箭的数量没有限制。 弓箭一旦被射出之后,可以无限地前进。我们想找到使得所有气球全部被引爆,所需的弓箭的最小数量。

Example:

1
2
3
4
5
6
7
8
输入:
[[10,16], [2,8], [1,6], [7,12]]

输出:
2

解释:
对于该样例,我们可以在x = 6(射爆[2,8],[1,6]两个气球)和 x = 11(射爆另外两个气球)。

题目详解

贪心算法。本题与 LeetCode435-无重叠区间 思路一致,只不过 LeetCode435-无重叠区间 是求重叠区间的个数,本题是求不重叠区间的个数。

  • 首先对数组按照区间的结尾从小到大进行排序。
  • 然后遍历数组,发现不重叠区间结果就递增,最后返回结果即可。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class LeetCode_00452 {

public int findMinArrowShots(int[][] points) {
if (points == null || points.length == 0) {
return 0;
}
// 使用 lambda 表达式创建 Comparator 会使程序运行时间变长,可以改为匿名内部类的形式
Arrays.sort(points, Comparator.comparingInt(o -> o[1]));
// Arrays.sort(points, new Comparator<int[]>() {
// @Override
// public int compare(int[] o1, int[] o2) {
// return Integer.compare(o1[1], o2[1]);
// }
// });
int res = 1;
int pre = points[0][1];
for (int i = 1; i < points.length; ++i) {
if (points[i][0] > pre) {
++res;
pre = points[i][1];
}
}
return res;
}
}