1 题目
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:
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).
2 尝试解
2.1 分析
在X-Y平面上,存在若干个圆形气球。每个气球在X轴上的投影都为一个整数闭合区间。现在沿Y轴方向发射弓箭,即弓箭的轨迹为X=K(K∈Z)。只要与弓箭轨迹接触(包括边界接触,即相切)的气球均会破裂。问至少要发射多少次弓箭才能射穿所有气球。
所有气球在X轴上投影的区间组成的数组为interval。将interval按照气球左边界排序。现在考虑左边界最大的气球,设其左边界为left。将所有气球分为3组,位于left左边的气球组A(interval[A][1]<left),位于left右边的气球组B(interval[B][0]>=left)和横跨left的气球C(interval[C][0]<left<=interval[C][1])。由于left为最大左边界,所以B组气球的左边界都为left。显然所有能射穿A组任意气球的弓箭无法射穿B组中的任意气球,反之亦然。所以要射穿B组全部气球,至少要一支独立于A组的弓箭。
现在考虑一支弓箭能不能射穿A组以外的全部气球,即B组和C组气球。显然让弓箭从X=left射出,由于B组气球左边界均为left,B组气球均被射穿;由于C组气球横跨left,C组气球也均被射穿。所以射穿B组和C组气球只要一支弓箭即可。
那么射穿A组气球至少要多少只弓箭,就变成了规模更小的原问题。所以该问题可以用动态规划和贪心算法解决。
实际上,该问题就是求区间interval不重叠(包括边界)的最大区间个数。
2.2 代码
class Solution {
public:
int findMinArrowShots(vector<vector<int>>& points) {
sort(points.begin(),points.end());
int result = 0;
int last_begin = INT_MAX;
for(int i = points.size()-1; i>= 0; i--){
if(result == 0 || points[i][1] < last_begin){
result += 1;
last_begin = points[i][0];
}
}
return result;
}
};
3 标准解
class Solution {
public:
int findMinArrowShots(vector<vector<int>>& points) {
int res = 0, i = 0, temp;
sort(points.begin(), points.end(), [](vector<int> a, vector<int> b){return a[1] < b[1];});
while (i < points.size()) {
res++;
temp = points[i++][1];
while (i < points.size() && points[i][0] <= temp) i++;
}
return res;
}
};