已知一个平面上有一定数量的气球,平面可以看做一个坐标系,在平面的x轴的不同位置安排弓箭手向y轴方向射箭,弓箭可以向y轴走无穷远;给定气球的宽度xstart<=x<=xend。问至少需要多少弓箭手,将全部气球打爆?
例如:四个气球: [[10,16],[2,8],[1,6],[7,12]],至少需要2个弓箭手。
#include<algorithm>
#include<vector>
bool cmp(const std::pair<int, int>& a, const std::pair<int, int>& b)
{
return a.first < b.first;
}
class Solution
{
public:
int findMinArrowShots(std::vector<std::pair<int, int>>& points)
{
if (points.size()==0)
{
return 0;
}
std::sort(points.begin(), points.end(), cmp);
int shoot_num = 1;
int shoot_begin = points[0].first;
int shoot_end = points[0].second;
for (unsigned i = 0; i < points.size(); i++)
{
if (points[i].first <= shoot_end)
{
shoot_begin = points[i].first;
if (shoot_end>points[i].second)
{
shoot_end = points[i].second;
}
}
else
{
shoot_num++;
shoot_begin = points[i].first;
shoot_end = points[i].second;
}
}
return shoot_num;
}
};
int main()
{
std::vector<std::pair<int, int>> points;
points.push_back(std::make_pair(10, 16));
points.push_back(std::make_pair(2, 8));
points.push_back(std::make_pair(1, 6));
points.push_back(std::make_pair(7, 12));
Solution solve;
printf("%d\n", solve.findMinArrowShots(points));
return 0;
}
运行结果:
2