没有输出的输入是不完整的

0%

leetcode-452-MinimumNumberOfArrowsToBurstBalloons

射箭,问射穿所有气球最少射几箭。
抽象出来之后,其实也是区间类型的题目。只是这次的排序方式相比与之前发生了点变化。

题目描述

There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it’s horizontal, y-coordinates don’t matter and hence the x-coordinates of start and end of the diameter suffice. Start is always smaller than end. There will be at most 104 balloons.

An arrow can be shot up exactly vertically from different points along the x-axis. A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend. There is no limit to the number of arrows that can be shot. An arrow once shot keeps travelling up infinitely. The problem is to find the minimum number of arrows that must be shot to burst all balloons.

Example

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

Output:
2

Explanation:
One way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) and another arrow at x = 11 (bursting the other two balloons).

解题思路

贪心算法

详细解释

射气球,总的来看,其实第一支箭一定会射在第一个气球的范围之内,比如说[1,6],而第二支箭一定是要射在第一个[1,6]覆盖不到的第一个气球的区间之内的。所以当我们按照他们的区间后端进行排序之后,就会很容易找到第一个不重合的气球,每次遇到一个与之前不重合的气球,就射一箭,从而可以实现最优解。

巧妙之处

  1. 之前的排序其实都是按照有序对的第一个元素进行排序,然后本题目是按照第二个元素排序,就可以使得题目变得非常的简单有效。
  2. 复习之前的lambda表达式的用法。

解题代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int findMinArrowShots(vector<vector<int>>& points) {
if(points.empty()) return 0;
sort(points.begin(), points.end(),[](vector<int>& a,vector<int>& b){
return (a[1] < b[1]);
});
int res = 1;
int end = points[0][1];
for(int i = 1; i < points.size(); i++){
if(points[i][0] > end){
res++;
end = points[i][1];
}
}
return res;
}
};

以上,本题结束!