题目描述
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).
代码
class Solution {
public:
static bool cmp(vector<int>& A, vector<int>& B) {
if (A[0] == B[0]) return A[1] < B[1];
return A[0] < B[0];
}
int findMinArrowShots(vector<vector<int>>& points) {
if (points.empty()) return 0;
int res = 0;
sort(points.begin(), points.end(), cmp);
int st = points[0][0], ed = points[0][1];
for (int i=1; i<points.size(); ++i) {
if (points[i][0] >= st && points[i][0] <= ed) {
st = max(points[i][0], st);
ed = min(points[i][1], ed);
}else {
res++;
st = points[i][0];
ed = points[i][1];
}
}
return res+1;
}
};

探讨如何通过计算找出用最少的箭矢数量来爆破所有水平排列的气球,涉及排序和区间覆盖算法,提供了一种有效的解决方案。
396

被折叠的 条评论
为什么被折叠?



