452 用最少数量的箭引爆气球

本文最后更新于:2021年3月15日 中午

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

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

给你一个数组 points ,其中 points [i] = [xstart,xend] ,返回引爆所有气球所必须射出的最小弓箭数。

示例 1:

1
2
3
输入:points = [[10,16],[2,8],[1,6],[7,12]]
输出:2
解释:对于该样例,x = 6 可以射爆 [2,8],[1,6] 两个气球,以及 x = 11 射爆另外两个气球

示例 2:

1
2
输入:points = [[1,2],[3,4],[5,6],[7,8]]
输出:4

示例 3:

1
2
输入:points = [[1,2],[2,3],[3,4],[4,5]]
输出:2

示例 4:

1
2
输入:points = [[1,2]]
输出:1

示例 5:

1
2
输入:points = [[2,3],[2,3]]
输出:1

提示:

  • 0 <= points.length <= 104
  • points[i].length == 2
  • -231 <= xstart < xend <= 231 - 1

Solution

参考:《算法小抄》5.8 、代码随想录

方法同 [435 无重叠区间](435 无重叠区间.md)

  • 贪心算法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# @lc code=start
class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
n = len(points)
if not n: return 0
points.sort(key = lambda a: a[1])
end = points[0][1]
cnt = 1
for i in range(1, n):
if points[i][0]>end:
cnt += 1
end = points[i][1]
return cnt
# @lc code=end

cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
private:
static bool cmp(const vector<int>& a, const vector<int>& b) {
return a[0] < b[0];
}
public:
int findMinArrowShots(vector<vector<int>>& points) {
if (points.size() == 0) return 0;
sort(points.begin(), points.end(), cmp);

int result = 1; // points 不为空至少需要一支箭
for (int i = 1; i < points.size(); i++) {
if (points[i][0] > points[i - 1][1]) { // 气球i和气球i-1不挨着,注意这里不是>=
result++; // 需要一支箭
}
else { // 气球i和气球i-1挨着
points[i][1] = min(points[i - 1][1], points[i][1]); // 更新重叠气球最小右边界
}
}
return result;
}
};

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!