1、題目
已知在一個平面上有一定數(shù)量的氣球神妹,平面可以看作一個坐標系颓哮,在平面的x軸的不同位 置安排弓箭手向y軸方向射箭,弓箭可以向y軸走無窮遠;給定氣球的寬度 xstart ≤ x ≤ xend
鸵荠,問至少需要多少弓箭手冕茅,將全部氣球打爆?
例如: 四個氣球 : [[10,16], [2,8], [1,6], [7,12]],至少需要2個弓箭手蛹找。
2姨伤、思考
3、貪心規(guī)律
4庸疾、算法思路
- 對各個氣球進行排序乍楚,按照氣球的左端點從小到大排序。
- 遍歷氣球數(shù)組届慈,同時維護一個射擊區(qū)間炊豪,在滿足可以將當前氣球射穿的
情況下凌箕,盡可能擊穿更多的氣球拧篮,每擊穿一個新的氣球词渤,更新一次射 擊區(qū)間(保證射擊區(qū)間可以將新氣球也擊穿)。 - 如果新的氣球沒辦法被擊穿了串绩,則需要增加一名弓箭手缺虐,即維護一個新的射擊區(qū)間(將該氣球擊穿),隨后繼續(xù)遍歷氣球數(shù)組礁凡。
5高氮、代碼實現(xiàn)
#include <vector>
#include <iostream>
using namespace std;
bool cmp(vector<int> p1, vector<int> p2)
{
return p1[0] < p2[0];
}
class Solution {
public:
int findMinArrowShots(vector< vector<int> >& points)
{
if (points.size() == 0)
return 0;
// 將points 中所有的點按左端點排序
sort(points.begin(), points.end(), cmp);
/*
for (int i = 0; i < points.size(); i++)
{
cout << points[i][0] << endl;
}
*/
// 左右端點以及shot數(shù)量
int shot_num = 1; // 至少有個氣球,至少有一只shot
int shot_begin = points[0][0];
int shot_end = points[0][1]; // 左右端點包含
// 從1開始遍歷
for (int i = 1; i < points.size(); i++)
{
if (points[i][0] <= shot_end)
{
shot_begin = points[i][0];
if (points[i][1] < shot_end) // 等于的情況下顷牌,不需要更新
{
shot_end = points[i][1];
}
}
else
{
shot_num ++;
shot_begin = points[i][0];
shot_end = points[i][1];
}
}
return shot_num;
}
};
int main()
{
vector< vector<int> > points;
for (int i = 0; i < 4; i++)
points.push_back(vector<int>());
points[0].push_back(10);
points[0].push_back(16);
points[1].push_back(2);
points[1].push_back(8);
points[2].push_back(1);
points[2].push_back(6);
points[3].push_back(7);
points[3].push_back(12);
Solution S;
int res = S.findMinArrowShots(points);
cout << "res: " << res << endl;
return 0;
}