Keshawn_lu's Blog

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

字数统计: 709阅读时长: 3 min
2020/11/23 Share

题目简介:

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

一支弓箭可以沿着 x 轴从不同点完全垂直地射出。在坐标 x 处射出一支箭,若有一个气球的直径的开始和结束坐标为

x_startx_end, 且满足 x_start ≤ x ≤ x_end,则该气球会被引爆。可以射出的弓箭的数量没有限制。 弓箭一旦被射出之后,可以无限地前进。我们想找到使得所有气球全部被引爆,所需的弓箭的最小数量。

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

示例 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
  • -2^31 <= x_start < x_end <= 2^31 - 1

思路:

首先以气球开始位置升序为第一关键字,气球结束位置升序为第二关键字将数组进行排序。

我们从头开始遍历,以确定每支弓箭所要射击的位置最远能到哪里。

为了确立最远的位置,我们还需要定义一个min_end,来保存可以击穿最多气球的最远边界(即弓箭射在这个边界位置,若有气球的开始位置大于这个值,则需要另一支弓箭来击穿了)。

我们定义当前遍历到的位置为points[i],对于i之后的气球,若points[i][1] >= points[pos][0] && points[pos][0] <= min_end,则说明这个位置的气球用同样的弓箭也可击穿,同时更新min_end = min(min_end, points[pos][1])

代码如下:

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
public:

static bool cmp(vector<int>& p1, vector<int>& p2){

if(p1[0] != p2[0])
return p1[0] < p2[0];

return p1[1] < p2[1];
}

int findMinArrowShots(vector<vector<int>>& points) {

sort(points.begin(), points.end(), cmp);

int res = 0;

int i = 0;
while(i < points.size()){

res++;

int pos = i + 1;
int min_end = points[i][1];

while(pos < points.size() &&
points[i][1] >= points[pos][0] &&
points[pos][0] <= min_end){

min_end = min(min_end, points[pos][1]);
pos++;
}

i = pos;
}

return res;
}
};
CATALOG
  1. 1. 题目简介:
  2. 2. 思路:
  3. 3. 代码如下: