您的位置:首页 > 其它

Minimum Number of Arrows to Burst Balloons问题及解法

2017-09-13 09:52 344 查看
问题描述:

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.

示例:
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:
int findMinArrowShots(vector<pair<int, int>>& points) {
if (points.empty()) return 0;
int res = 1;
auto cmp = [](pair<int, int> a, pair<int, int> b){
return a.second < b.second;
};
sort(points.begin(), points.end(), cmp);
int start = points[0].first, end = points[0].second;
for (int i = 1; i < points.size(); i++)
{
if (points[i].first <= end && points[i].first > start)
{
start = points[i].first;
}
else if (points[i].first > end)
{
res++;
start = points[i].first;
end = points[i].second;
}
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: